package com.alibaba.citrus.cr.unified.inventory.facade.service;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.log.ModuleEnum;
import com.alibaba.citrus.cr.common.util.JsonUtil;
import com.alibaba.citrus.cr.common.util.TimeUtil;
import com.alibaba.citrus.cr.unified.inventory.model.WmsMainOrder;
import com.alibaba.citrus.cr.unified.inventory.repository.AllocateApplyOrderReadRepository;
import com.alibaba.citrus.cr.unified.inventory.repository.AllocateOrderDetailReadRepository;
import com.alibaba.citrus.cr.unified.inventory.repository.AllocateOrderReadRepository;
import com.alibaba.citrus.cr.unified.inventory.utils.DateUtils;
import com.alibaba.citrus.cr.unified.inventory.utils.EnumUtils;
import com.alibaba.citrus.cr.unified.inventory.utils.InfoUtil;
import com.alibaba.cloud.retail.store.api.service.WarehouseQueryService;
import com.alibaba.cloud.retail.store.request.warehouse.WarehouseQueryRequest;
import com.alibaba.cz.base.model.store.WarehouseSDO;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.log.model.OpLogDateTypeEnum;
import com.alibaba.cz.item.normal.scitem.api.ScItemSearchAbilityService;
import com.alibaba.cz.item.normal.scitem.model.search.ScItemSearchAbilityRequest;
import com.alibaba.cz.item.normal.scitem.model.search.ScItemSearchAbilityResponse;
import com.alibaba.cz.item.normal.scitem.model.search.ScItemSearchReqAbilityDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.crplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.model.dto.OperateLogDiff;
import com.epoch.app.crplatformenhance.model.dto.OperateQueryInfoRequest;
import com.epoch.app.crplatformenhance.model.dto.PageQueryAddressListRequest;
import com.epoch.app.crplatformenhance.model.dto.PageQueryAddressListResponse;
import com.epoch.app.crplatformenhance.queryoperatelog.service.QueryOperateLogService;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.crunifiedinventory.api.allocateorderread.dto.*;
import com.epoch.app.crunifiedinventory.api.allocateorderread.service.AllocateOrderReadService;
import com.epoch.app.crunifiedinventory.consignmentorder.dto.QueryConsignmentOrderByStoOrderIdsRequest;
import com.epoch.app.crunifiedinventory.consignmentorder.model.ConsignmentOrder;
import com.epoch.app.crunifiedinventory.consignmentorder.service.ConsignmentOrderService;
import com.epoch.app.crunifiedinventory.consignmentorderline.dto.BatchQueryRequest;
import com.epoch.app.crunifiedinventory.consignmentorderline.model.ConsignmentOrderLine;
import com.epoch.app.crunifiedinventory.consignmentorderline.service.ConsignmentOrderLineService;
import com.epoch.app.crunifiedinventory.contants.CrUnifiedInventoryConstants;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorder.dto.QueryListByIdsRequest;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorder.model.AllocateApplyOrder;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorder.service.AllocateApplyOrderService;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorderdetail.dto.QueryAllocateApplyOrderDetailListByAllocateApplyOrderIdsRequest;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorderdetail.model.AllocateApplyOrderDetail;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorderdetail.service.AllocateApplyOrderDetailService;
import com.epoch.app.crunifiedinventory.domain.allocateorder.dto.AllocateOrderLoadListRequest;
import com.epoch.app.crunifiedinventory.domain.allocateorder.model.AllocateOrder;
import com.epoch.app.crunifiedinventory.domain.allocateorder.service.AllocateOrderService;
import com.epoch.app.crunifiedinventory.domain.allocateorderdetail.dto.AllocateOrderDetailLoadListRequest;
import com.epoch.app.crunifiedinventory.domain.allocateorderdetail.model.AllocateOrderDetail;
import com.epoch.app.crunifiedinventory.domain.allocateorderdetail.service.AllocateOrderDetailService;
import com.epoch.app.crunifiedinventory.dto.request.*;
import com.epoch.app.crunifiedinventory.dto.response.*;
import com.epoch.app.crunifiedinventory.model.dto.*;
import com.epoch.app.crunifiedinventory.model.enums.AllocateOrderStatus;
import com.epoch.app.crunifiedinventory.model.enums.WmsStatusEnum;
import com.epoch.app.crunifiedinventory.ouiallocateorderdetailindex.model.OuiAllocateOrderDetailIndex;
import com.epoch.app.crunifiedinventory.ouiallocateorderdetailindex.service.OuiAllocateOrderDetailIndexService;
import com.epoch.app.crunifiedinventory.sdo.AllocateOrderDetailSDO;
import com.epoch.app.crunifiedinventory.sdo.AllocateOrderSDO;
import com.epoch.app.crunifiedinventory.sdo.AllocateOrderWithOrderDetailsSDO;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateOrderShipTypeEnums;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateOrderTypeEnum;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zhangguoqing
 * @date 2021/08/25
 */
@Component
@Primary
public class AllocateOrderReadServiceImpl implements AllocateOrderReadService {
    private Log log = Log.getLogger(AllocateOrderReadServiceImpl.class);

    @Resource
    AllocateOrderReadRepository allocateOrderReadRepository;
    @Resource
    AllocateOrderDetailReadRepository allocateOrderDetailReadRepository;
    @Resource
    AllocateApplyOrderReadRepository allocateApplyOrderReadRepository;
    @Autowired
    CrUnifiedInventoryService unifiedInventoryService;
    @Resource
    OuiAllocateOrderDetailIndexService detailIndexService;
    @Resource
    CrPlatformEnhanceService otsPlatformEnhanceService;
    @Resource
    private QueryOperateLogService queryOperateLogService;
    @Resource
    private BaseDataService baseDataService;
    @Resource
    AllocateOrderService allocateOrderService;
    @Resource
    private AllocateApplyOrderService allocateApplyOrderService;
    @Resource
    private AllocateApplyOrderDetailService allocateApplyOrderDetailService;
    @Resource
    private ConsignmentOrderService consignmentOrderService;
    @Resource
    private ConsignmentOrderLineService consignmentOrderLineService;

    @Resource(name = "allocateApplyTaskExecutor")
    private ThreadPoolTaskExecutor allocateApplyTaskExecutor;
    @Resource
    private AllocateOrderDetailService allocateOrderDetailService;

    @Resource
    private OrganizationQueryService organizationQueryService;
    @DubboReference
    private ScItemSearchAbilityService scItemSearchAbilityService;
    @DubboReference
    private WarehouseQueryService warehouseQueryService;


    //    public static final String PREFIX = "";
    public static final Integer MAX_PAGE_SIZE = 1000;
    //分子公司业务员
    private static final String SALES_MAN_ROLE_CODE = "001";
    private static final String UNKNOWN = "unknown";
    private static final String SYSTEM = "系统";

    @Override
    public ShipMethodResponse shipMethod() {
        ShipMethodResponse sh = new ShipMethodResponse();
        List<ShipMethodObj> shipMethodObjs = Lists.newArrayList();
        for (AllocateOrderShipTypeEnums value : AllocateOrderShipTypeEnums.values()) {
            ShipMethodObj obj = new ShipMethodObj();
            obj.setLabel(value.getDesc());
            obj.setValue(value.getType() +"");
            shipMethodObjs.add(obj);
        }
        sh.setSuccess(true);
        sh.setResult(shipMethodObjs);
        return sh;
    }

    public AllocateOrderDetailResponse allocateOrderDetailResponse(List<AllocateOrderDetailSDO> sdos){
        AllocateOrderDetailResponse response = new AllocateOrderDetailResponse();
        List<AllocateOrderDetailVO> detailVOS = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(sdos)){
            sdos.forEach(x->{

            });
        }
        response.setSearchResult(detailVOS);
        return response;
    }
    public static void setWarehouse(AllocateOrderDetailVO vo , AllocateOrderSDO sdo,
                                    List<AllocateOrderDetailGetWarehouseResponse> responses){
        List<AllocateOrderDetailGetWarehouseResponse> r  = responses.stream().filter(w->
                Objects.equals(w.getId(),sdo.getShipWarehouseId())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(r)){
            vo.setShipWarehouseName(r.get(0).getName());
        }
        r = responses.stream().filter(w->
                Objects.equals(w.getId(),sdo.getReceiveWarehouseId())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(r)){
            vo.setReceiveWarehouseName(r.get(0).getName());
        }
    }

    public static void setOrg(AllocateOrderDetailVO vo ,AllocateOrderSDO sdo,
                              List<AllocateOrderDetailBatchGetOrgResponse> batchGetOrgResponses){
        List<AllocateOrderDetailBatchGetOrgResponse> allocateOrderDetailBatchGetOrgResponses =
                batchGetOrgResponses.stream().filter(org->Objects.equals(sdo.getApplyOrgId(),org.getId()))
                        .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(allocateOrderDetailBatchGetOrgResponses)){
            vo.setApplyOrgName(allocateOrderDetailBatchGetOrgResponses.get(0).getName());
            vo.setBorrowOrgName(allocateOrderDetailBatchGetOrgResponses.get(0).getName());
        }
    }
    public static void setCustomer(AllocateOrderDetailVO vo ,AllocateOrderSDO sdo,
                                   List<AllocateOrderDetailGetCustomerResponse> customerResponses){
        List<AllocateOrderDetailGetCustomerResponse> responses =
                customerResponses.stream().filter(x->Objects.equals(x.getCode(),sdo.getCustomer()))
                        .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(responses)){
            vo.setCustomer(responses.get(0).getName());
            vo.setCustomerAddress(responses.get(0).getLocationAddress());
        }
    }

    public static void setScItem(AllocateOrderDetailVO vo ,
                                 List<AllocateOrderDetailBatchGetScItemResponse> responses){
        List<AllocateOrderDetailBatchGetScItemResponse> rs =  CollectionUtils.emptyIfNull(responses)
                .stream()
                .filter(x->Objects.equals(vo.getScItemId(),x.getScItemId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(rs)){
            vo.setScItemId(rs.get(0).getScItemId());
            vo.setScItemCode(rs.get(0).getScItemCode());
            vo.setScItemName(rs.get(0).getTitle());
        }
    }

    /**
     * 调拨单客户收货地址下拉列表
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<List<AllocateOrderCustomerAddressDTO>> getCustomerAddressList() {
        PageQueryAddressListRequest request = new PageQueryAddressListRequest();
//        request.setSize(2000);
        PageQueryAddressListResponse response = otsPlatformEnhanceService.pageQueryAddressList(request);
        List<AllocateOrderCustomerAddressDTO> list = Lists.newArrayList();
        if (response != null && CollectionUtils.isNotEmpty(response.getResult())){
            for (Object obj : response.getResult()) {
                JSONObject js = JSON.parseObject(JSON.toJSONString(obj));
                if (js != null){
                    AllocateOrderCustomerAddressDTO dto = new AllocateOrderCustomerAddressDTO();
                    dto.setLabel(js.getString("address"));
                    dto.setValue(js.getString("addressCode"));
                    list.add(dto);
                }
            }
        }
        return Result.success(list);
    }

    public void handleSearchConditions(AllocateOrderDetailSearchRequest request){
        if(StringUtils.isNotBlank(request.getCode())){
            request.setCode(request.getCode().trim());
        }
        if (StringUtils.isNotBlank(request.getAllocateApplyOrderCode())){
            request.setAllocateApplyOrderCode(request.getAllocateApplyOrderCode().trim());
        }
        if (StringUtils.isNotBlank(request.getOutAllocateOrderId())){
            request.setOutAllocateOrderId(request.getOutAllocateOrderId().trim());
        }
        //处理单据日期
        if (CollectionUtils.isNotEmpty(request.getDocDate())){
//            request.setDocDateBegin(request.getDocDate().get(0));
            if (request.getDocDate().get(0)!=null){
                request.setDocDateBeginLong(TimeUtil.getTime(request.getDocDate().get(0)));
            }
            if (request.getDocDate().get(1) != null){
                request.setDocDateEndLong(TimeUtil.getSearchEndTime(request.getDocDate().get(1)));
            }
        }
        if (CollectionUtils.isNotEmpty(request.getCreateTime())){
            if (request.getCreateTime().get(0) != null){
                request.setCreateTimeBeginLong(TimeUtil.getTime(request.getCreateTime().get(0)));
            }
            if (request.getCreateTime().get(1) != null){
                request.setCreateTimeEndLong(TimeUtil.getSearchEndTime(request.getCreateTime().get(1)));
            }
        }
        if (CollectionUtils.isNotEmpty(request.getShipTime())){
            if (request.getShipTime().get(0)!=null){
                request.setShipTimeBeginLong(TimeUtil.getTime(request.getShipTime().get(0)));
            }
            if (request.getShipTime().get(1) != null){
                request.setShipTimeEndLong(TimeUtil.getSearchEndTime(request.getShipTime().get(1)));
            }
        }
        if (CollectionUtils.isNotEmpty(request.getReceiveTime())){
            if(request.getReceiveTime().get(0)!=null){
                request.setReceiveTimeBeginLong(TimeUtil.getTime(request.getReceiveTime().get(0)));
            }
            if (request.getReceiveTime().get(1)!=null){
                request.setReceiveTimeEndLong(TimeUtil.getSearchEndTime(request.getReceiveTime().get(1)));
            }
        }
        if (CollectionUtils.isNotEmpty(request.getExpectedDeliveryDate())){
            if (request.getExpectedDeliveryDate().get(0)!= null){
                request.setExpectedDeliveryDateBeginLong(TimeUtil.getTime(request.getExpectedDeliveryDate().get(0)));
            }
            if (request.getExpectedDeliveryDate().get(1)!=null){
                request.setExpectedDeliveryDateEndLong(TimeUtil.getSearchEndTime(request.getExpectedDeliveryDate().get(1)));
            }
        }
        if (CollectionUtils.isNotEmpty(request.getConfirmTime())){
            if (request.getConfirmTime().get(0) != null){
                request.setConfirmTimeBeginLong(TimeUtil.getTime(request.getConfirmTime().get(0)));
            }
            if (request.getConfirmTime().get(1) != null){
                request.setConfirmTimeEndLong(TimeUtil.getSearchEndTime(request.getConfirmTime().get(1)));
            }
        }
        if (CollectionUtils.isNotEmpty(request.getDeliveryDate())){
            if (request.getDeliveryDate().get(0) != null){
                request.setDeliveryDateBeginLong(TimeUtil.getTime(request.getDeliveryDate().get(0)));
            }
            if (request.getDeliveryDate().get(1) != null){
                request.setDeliveryDateEndLong(TimeUtil.getSearchEndTime(request.getDeliveryDate().get(1)));
            }
        }
        if (StringUtils.isNotBlank(request.getTypes())){
            String[] typeArray = request.getTypes().split(",");
            request.setTypeList(Arrays.asList(typeArray));
        }
        if (StringUtils.isNotBlank(request.getCreator())){
            request.setCreator(request.getCreator());
        }
        if (CollectionUtils.isNotEmpty(request.getSubmitTime())){
            if (request.getSubmitTime().get(0) != null){
                request.setSubmitTimeBeginLong(TimeUtil.getTime(request.getSubmitTime().get(0)));
            }
            if (request.getSubmitTime().get(1) != null){
                request.setSubmitTimeEndLong(TimeUtil.getSearchEndTime(request.getSubmitTime().get(1)));
            }
        }
        //2022.07.04 调拨单主单和子单支持多选
        List mainStatusList = null;
        List subStatusList = null;
        if (request.getStatus() != null){
            if (CollectionUtils.isEmpty(request.getStatusList())){
                request.setStatusList(Lists.newArrayList(request.getStatus()));
            }else {
                request.getStatusList().add(request.getStatus());
            }
        }
        if (request.getLineStatus() != null){
            if (CollectionUtils.isEmpty(request.getLineStatusList())){
                request.setLineStatusList(Lists.newArrayList(request.getLineStatus()));
            }else {
                request.getLineStatusList().add(request.getLineStatus());
            }
        }

        request.setDir("subId");
//        request.setDir("mainDocDate");
        request.setAsc(false);
    }

    /**
     * 批量获取组织
     * @param result
     * @return
     */
    public Map<String,String> getOrgMap(Result<List<OuiAllocateOrderDetailIndex>> result){
        Map<String,String> map = Maps.newHashMap();
        if (result == null || CollectionUtils.isEmpty(result.getResult())){
            return map;
        }
        //获取到所有的组织id 提报组织id
        List<String> orgIdList = result.getResult().stream().filter(index -> StringUtils.isNotBlank(index.getMainApplyOrgId()))
                .map(OuiAllocateOrderDetailIndex::getMainApplyOrgId).distinct().collect(Collectors.toList());

        List<String> shipReceiveOrgIdList = result.getResult().stream()
                .filter(Objects::nonNull)
                .flatMap(index -> Stream.of(index.getMainShipOrgId(),index.getMainReceiveOrgId()))
                .filter(x->StringUtils.isNotBlank(x))
                .distinct().collect(Collectors.toList());
        if(CollectionUtils.isEmpty(orgIdList)){
            orgIdList = Lists.newArrayList();
        }else if (CollectionUtils.isEmpty(shipReceiveOrgIdList)){
            shipReceiveOrgIdList = Lists.newArrayList();
        }
        orgIdList.addAll(shipReceiveOrgIdList);

        //发货收货仓的组织id name
        AllocateOrderDetailBatchGetOrgRequest batchGetOrgRequest = new AllocateOrderDetailBatchGetOrgRequest();
        batchGetOrgRequest.setOrgIds(orgIdList);
        List<AllocateOrderDetailBatchGetOrgResponse> batchGetOrgResponses = allocateOrderDetailReadRepository.batchGetOrg(batchGetOrgRequest);
//            Map<String,String> orgMap = batchGetOrgResponses.stream().collect(Collectors.toMap(AllocateOrderDetailBatchGetOrgResponse::getId,
//                    AllocateOrderDetailBatchGetOrgResponse::getName));
        if (CollectionUtils.isEmpty(batchGetOrgResponses))return map;
        Map<String,String> orgMap = batchGetOrgResponses.stream().collect(
                HashMap::new,(hashMap,org) -> hashMap.put(org.getId(),org.getName()),HashMap::putAll);
        return orgMap;
    }

    public static Map<String,String> getWmsNameMap(Result<List<OuiAllocateOrderDetailIndex>> result){
        Map<String,String> map = Maps.newHashMap();
        if (result == null || CollectionUtils.isEmpty(result.getResult())){
            return map;
        }
        List<String> ids = result.getResult().stream().filter(Objects::nonNull)
                .flatMap(x->Stream.of(x.getMainShipAreaId(),x.getMainReceiveAreaId(),
                        x.getMainShipWarehouseId(),x.getMainReceiveWarehouseId()))
                .filter(Objects::nonNull)
                .filter(y->StringUtils.isNotBlank(y))
                .distinct()
                .collect(Collectors.toList());
//                        .filter(x->StringUtils.isNotBlank(x.getMainShipAreaId()))
        Map<String, String> wmsMap = InfoUtil.getWmsNameMap(ids);
        return wmsMap;
    }

    public static Map<String,AllocateOrderGetCustomerResponse> getBranchCustomerMap(Result<List<OuiAllocateOrderDetailIndex>> result){
        Map<String,AllocateOrderGetCustomerResponse> map = Maps.newHashMap();
        if (result == null || CollectionUtils.isEmpty(result.getResult())){
            return map;
        }
        List<String> codes = result.getResult().stream().filter(Objects::nonNull)
                .filter(x->StringUtils.isNotBlank(x.getMainBranchCustomersCode()))
                .map(OuiAllocateOrderDetailIndex::getMainBranchCustomersCode)
                .distinct()
                .collect(Collectors.toList());
        map = InfoUtil.getCustomerMap(codes);
        return map;
    }

    /** 中台openAPI 查询仓库 **/
    public Map<String,WmsSDO> composeWmsMap(Result<List<OuiAllocateOrderDetailIndex>> result){
        Map<String,WmsSDO> map = Maps.newHashMap();
        if (result == null || CollectionUtils.isEmpty(result.getResult())){
            return map;
        }
        List<String> ids = result.getResult().stream().filter(Objects::nonNull)
                .flatMap(x->Stream.of(x.getMainShipAreaId(),x.getMainReceiveAreaId(),
                        x.getMainShipWarehouseId(),x.getMainReceiveWarehouseId(),
                        x.getMainTransferWarehouseId()))
                .filter(StringUtils::isNotBlank)
                .distinct()
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(ids)){
            WarehouseQueryRequest warehouseQueryRequest = new WarehouseQueryRequest();
            warehouseQueryRequest.setWarehouseIds(ids);
            warehouseQueryRequest.setSize(ids.size());
            log.info("batchQueryList_request:{}",JSON.toJSONString(warehouseQueryRequest));
            com.alibaba.cz.base.tool.result.Result<List<WarehouseSDO>> listResult =  warehouseQueryService.batchQueryList(warehouseQueryRequest);
            log.info("batchQueryList_result:{}",JSON.toJSONString(listResult));
            Optional.ofNullable(listResult).map(com.alibaba.cz.base.tool.result.Result::getResult).orElse(Lists.newArrayList())
                    .stream().forEach(warehouseSDO -> {
                        WmsSDO wmsSDO = new WmsSDO();
                        wmsSDO.setName(warehouseSDO.getName());
                        wmsSDO.setCode(warehouseSDO.getCode());
                        wmsSDO.setId(warehouseSDO.getId());
                        wmsSDO.setType(Optional.ofNullable(warehouseSDO.getType()).map(String::valueOf).orElse(null));
                        wmsSDO.setWarehouseId(warehouseSDO.getParentId());
                        Map<String, String> features = warehouseSDO.getFeatures();
                        if (MapUtils.isNotEmpty(features)){
                            wmsSDO.setFactoryCode(features.get("factoryCode"));
                            wmsSDO.setInventoryCode(features.get("warehouseCode"));
                            wmsSDO.setSapCompanyCode(features.get("sapCompanyCode"));
                            wmsSDO.setSapSalesBPCode(features.get("sapSaleBPCode"));
                            wmsSDO.setSapDeliveryBPCode(features.get("sapDeliveryBPCode"));
                            wmsSDO.setSapInternalDeliveryBPCode(features.get("sapInternalDeliveryBPCode"));
                            wmsSDO.setSapInternalSalesBPCode(features.get("sapInternalSalesBPCode"));
                            wmsSDO.setSapSalesOrgId(features.get("saleOrgId"));
                        }
                        wmsSDO.setContactPerson(warehouseSDO.getContactName());
                        wmsSDO.setPhone(warehouseSDO.getContactPhone());
                        wmsSDO.setAddress(warehouseSDO.getAddressAppend());
                        map.put(warehouseSDO.getId(),wmsSDO);
                    });
        }
        return map;
    }

    public static Map<String,WmsSDO> getWmsMap(Result<List<OuiAllocateOrderDetailIndex>> result){
        Map<String,WmsSDO> map = Maps.newHashMap();
        if (result == null || CollectionUtils.isEmpty(result.getResult())){
            return map;
        }
        List<String> ids = result.getResult().stream().filter(Objects::nonNull)
                .flatMap(x->Stream.of(x.getMainShipAreaId(),x.getMainReceiveAreaId(),
                        x.getMainShipWarehouseId(),x.getMainReceiveWarehouseId()))
                .filter(Objects::nonNull)
                .filter(y->StringUtils.isNotBlank(y))
                .distinct()
                .collect(Collectors.toList());
        Map<String,WmsSDO> wmsSDOMap = InfoUtil.getWmsMap(ids);
        return wmsSDOMap;
    }

//    public Map<String,String> areaMap(){
//        AllocateOrderDetailGetBatchWarehouseRequest batchWarehouseRequest = new AllocateOrderDetailGetBatchWarehouseRequest();
////        batchWarehouseRequest.setWarehouseIds(warehouseIds);
//        List<AllocateOrderDetailGetWarehouseResponse> warehouseResponses =
//                allocateOrderDetailReadRepository.batchGetWarehouse(batchWarehouseRequest);
//        return null;
//    }

    /**
     *  通过地址获取到客户信息map 转成 客户编码->客户信息map
     * @param addressMap
     * @return
     */
    public Map<String,AllocateOrderGetCustomerResponse> getCustomerMapByCustomerCodeFromMap(
            Map<String,AllocateOrderGetCustomerResponse> addressMap){
        Map<String,AllocateOrderGetCustomerResponse> map = Maps.newHashMap();
        if (addressMap == null){
            return map;
        }
        map = addressMap.values().stream().filter(Objects::nonNull)
                .filter(x->StringUtils.isNotBlank(x.getCustomer()))
                .collect(HashMap::new,(hash,v) -> hash.put(v.getCustomer(),v),HashMap::putAll);

        return map;
    }



    /**
     * 获取客户信息map
     * @param result
     * @return
     */
    public Map<String,AllocateOrderGetCustomerResponse> getCustomerResponseMap(Result<List<OuiAllocateOrderDetailIndex>> result){
        Map<String,AllocateOrderGetCustomerResponse> map = Maps.newHashMap();
        if (result == null || CollectionUtils.isEmpty(result.getResult())){
            return map;
        }
        List<String> addressCodeList = result.getResult().stream().filter(Objects::nonNull)
                .filter(x -> StringUtils.isNotBlank(x.getMainAddressCode()))
                .map(OuiAllocateOrderDetailIndex::getMainAddressCode)
                .distinct().collect(Collectors.toList());
        List<AllocateOrderGetCustomerResponse> responses = InfoUtil.getCustomerByAddressCodes(addressCodeList);
        if (CollectionUtils.isNotEmpty(responses)){
            //TODO 余红伟  这个地方需要改下，需要根据客户id查找数据
            for (AllocateOrderGetCustomerResponse allocateOrderGetCustomerResponse : responses){
                if (Objects.isNull(map.get(allocateOrderGetCustomerResponse.getAddressCode()))) {
                    map.put(allocateOrderGetCustomerResponse.getAddressCode(), allocateOrderGetCustomerResponse);
                }
            }
//            map = responses.stream().collect(HashMap::new,(hash,cr)->hash.put(cr.getAddressCode(),cr),HashMap::putAll);
        }
        return map;
    }

    /** 中台查询 货品  **/
    public Map<String,AllocateOrderDetailBatchGetScItemResponse> composeScItemResponseMap(Result<List<OuiAllocateOrderDetailIndex>> result){
        Map<String,AllocateOrderDetailBatchGetScItemResponse> map = Maps.newHashMap();
        if (result == null || CollectionUtils.isEmpty(result.getResult())){
            return map;
        }
        List<String> scItemIdList = result.getResult().stream().filter(Objects::nonNull)
                .filter(x->StringUtils.isNotBlank(x.getSubScItemId()))
                .map(OuiAllocateOrderDetailIndex::getSubScItemId)
                .distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(scItemIdList)){
            ScItemSearchAbilityRequest scItemSearchAbilityRequest = new ScItemSearchAbilityRequest();
            ScItemSearchReqAbilityDTO scItemSearchReqAbilityDTO = new ScItemSearchReqAbilityDTO();
            scItemSearchReqAbilityDTO.setScItemIds(scItemIdList);
            scItemSearchAbilityRequest.setSearchReqDTO(scItemSearchReqAbilityDTO);
            scItemSearchAbilityRequest.setPageSize(scItemIdList.size());
            com.alibaba.cz.base.tool.result.Result<ScItemSearchAbilityResponse> scItemSearchAbilityResponseResult = scItemSearchAbilityService.searchFromDB(scItemSearchAbilityRequest);
            Optional.ofNullable(scItemSearchAbilityResponseResult).map(com.alibaba.cz.base.tool.result.Result::getResult).map(ScItemSearchAbilityResponse::getSearchResult)
                    .orElse(Lists.newArrayList()).stream()
                    .forEach(scItemSDO -> {
                        AllocateOrderDetailBatchGetScItemResponse response = new AllocateOrderDetailBatchGetScItemResponse();
                        response.setScItemId(scItemSDO.getScItemId());
                        response.setTitle(scItemSDO.getTitle());
                        response.setScItemCode(scItemSDO.getOuterId());
                        response.setFeatures(scItemSDO.getFeatures());
                        map.put(scItemSDO.getScItemId(),response);
                    });
        }
        return map;
    }

    public static Map<String,AllocateOrderDetailBatchGetScItemResponse> getScItemResponseMap(Result<List<OuiAllocateOrderDetailIndex>> result){
        Map<String,AllocateOrderDetailBatchGetScItemResponse> map = Maps.newHashMap();
        if (result == null || CollectionUtils.isEmpty(result.getResult())){
            return map;
        }
        List<String> scItemIdList = result.getResult().stream().filter(Objects::nonNull)
                .filter(x->StringUtils.isNotBlank(x.getSubScItemId()))
                .map(OuiAllocateOrderDetailIndex::getSubScItemId)
                .distinct().collect(Collectors.toList());
        Map<String,AllocateOrderDetailBatchGetScItemResponse> targetMap = InfoUtil.getScItemMap(scItemIdList);
        if(targetMap == null){
            return map;
        }
        return targetMap;
    }

    public Map<String,AllocateApplyOrder> queryAllocateApplyOrderMap(List<String> ids){
        Map<String,AllocateApplyOrder> allocateApplyOrderMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(ids)) {
            QueryListByIdsRequest queryListByIdsRequest = new QueryListByIdsRequest();
            queryListByIdsRequest.setIds(ids);
            Result<List<AllocateApplyOrder>> allocateApplyOrderResult = allocateApplyOrderService.queryListByIds(queryListByIdsRequest);
            if (Objects.nonNull(allocateApplyOrderResult) && CollectionUtils.isNotEmpty(allocateApplyOrderResult.getResult())) {
                for (AllocateApplyOrder allocateApplyOrder : allocateApplyOrderResult.getResult()) {
                    allocateApplyOrderMap.put(allocateApplyOrder.getId().toString(), allocateApplyOrder);
                }
            }
        }
        return allocateApplyOrderMap;
    }

    //获取预报单明细
    public Map<String,List<AllocateApplyOrderDetail>> queryAllocateApplyOrderDetailMap(List<String> ids){
        Map<String,List<AllocateApplyOrderDetail>> map = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(ids)){
            QueryAllocateApplyOrderDetailListByAllocateApplyOrderIdsRequest queryAllocateApplyOrderDetailListByAllocateApplyOrderIdsRequest = new QueryAllocateApplyOrderDetailListByAllocateApplyOrderIdsRequest();
            queryAllocateApplyOrderDetailListByAllocateApplyOrderIdsRequest.setAllocateApplyOrderIds(ids);
            queryAllocateApplyOrderDetailListByAllocateApplyOrderIdsRequest.setLimit(1000);
            Result<List<AllocateApplyOrderDetail>> listResult = allocateApplyOrderDetailService.queryAllocateApplyOrderDetailListByAllocateApplyOrderIds(queryAllocateApplyOrderDetailListByAllocateApplyOrderIdsRequest);
            if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                return listResult.getResult().stream().collect(Collectors.groupingBy(x-> x.getAllocateApplyOrderId().toString()));
            }
        }
        return map;
    }



    //要求交货单号根据明细的来
    public Map<String,String> getConsignmentOrderMap(List<String> codes){
        Map<String,String> map = Maps.newHashMap();
        if (CollectionUtils.isEmpty(codes)){
            return map;
        }
        QueryConsignmentOrderByStoOrderIdsRequest queryConsignmentOrderByStoOrderIdsRequest = new QueryConsignmentOrderByStoOrderIdsRequest();
        // queryConsignmentOrderByStoOrderIdsRequest.setStoOrderIds(codes);
        queryConsignmentOrderByStoOrderIdsRequest.setOutAllocateIds(codes);
        Result<List<ConsignmentOrder>> consignmentOrderResult = consignmentOrderService.queryConsignmentOrderByStoOrderIds(queryConsignmentOrderByStoOrderIdsRequest);
        if (consignmentOrderResult != null && CollectionUtils.isNotEmpty(consignmentOrderResult.getResult())){
            List<ConsignmentOrder> collect = consignmentOrderResult.getResult().stream().
                    filter(x -> Objects.equals(x.getStatus(), 1)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect)){
                return map;
            }
            List<Long> ids = collect.stream().map(ConsignmentOrder::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(ids)){
                BatchQueryRequest batchQueryRequest = new BatchQueryRequest();
                batchQueryRequest.setConsignmentOrderIds(ids.stream().map(String::valueOf).collect(Collectors.toList()));
                batchQueryRequest.setLimit(700);
                //查询出交货单
                Result<List<ConsignmentOrderLine>> listResult = consignmentOrderLineService.batchQuery(batchQueryRequest);
                if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                    List<ConsignmentOrder> orders = collect;
                    List<ConsignmentOrderLine> lines = listResult.getResult();
                    //先根据调拨单号分组
                    //循环得到 code,scItemId --> 交货单号..
                    for (ConsignmentOrder order : orders) {
                        for (ConsignmentOrderLine line : lines) {
                            if (order.getId() != null && StringUtils.isNotBlank(line.getConsignmentOrderId())
                                    && line.getConsignmentOrderId().equals(order.getId().toString())){
                                String key = order.getOuterStoOrderId() + "," + line.getScItemId();
                                String outerDeliveryOrderId = map.get(key);
                                if (StringUtils.isBlank(outerDeliveryOrderId)){
                                    map.put(key,order.getOuterDeliveryOrderId());
                                }else {
                                    if (StringUtils.isNotBlank(order.getOuterDeliveryOrderId())){
                                        map.put(key,map.get(key) + "," + order.getOuterDeliveryOrderId());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return map;

    }

    public Map<String,String> getConsignmentOrderMapWithIsECommerceOrder(List<OuiAllocateOrderDetailIndex> indices ){
        List<String> codes = indices.stream().map(OuiAllocateOrderDetailIndex::getMainOutAllocateOrderId).map(InfoUtil::deleteZeroPrefix)
                .filter(Objects::nonNull).collect(Collectors.toList());
        Map<String,String> map = Maps.newHashMap();
        if (CollectionUtils.isEmpty(codes)){
            return map;
        }
        QueryConsignmentOrderByStoOrderIdsRequest queryConsignmentOrderByStoOrderIdsRequest = new QueryConsignmentOrderByStoOrderIdsRequest();
        // queryConsignmentOrderByStoOrderIdsRequest.setStoOrderIds(codes);
        queryConsignmentOrderByStoOrderIdsRequest.setOutAllocateIds(codes);
        Result<List<ConsignmentOrder>> consignmentOrderResult = consignmentOrderService.queryConsignmentOrderByStoOrderIds(queryConsignmentOrderByStoOrderIdsRequest);
        if (consignmentOrderResult != null && CollectionUtils.isNotEmpty(consignmentOrderResult.getResult())){
            List<ConsignmentOrder> collect = consignmentOrderResult.getResult().stream().
                    filter(x -> Objects.equals(x.getStatus(), 1)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect)){
                return map;
            }
            List<Long> ids = collect.stream().map(ConsignmentOrder::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(ids)){
                BatchQueryRequest batchQueryRequest = new BatchQueryRequest();
                batchQueryRequest.setConsignmentOrderIds(ids.stream().map(String::valueOf).collect(Collectors.toList()));
                batchQueryRequest.setLimit(700);
                //查询出交货单
                Result<List<ConsignmentOrderLine>> listResult = consignmentOrderLineService.batchQuery(batchQueryRequest);
                if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                    List<ConsignmentOrder> orders = collect;
                    List<ConsignmentOrderLine> lines = listResult.getResult();
                    //先根据调拨单号分组
                    //循环得到 code,scItemId --> 交货单号..
                    for (ConsignmentOrder order : orders) {
                        String receiveOrgId = indices.stream().filter(x -> Objects.equals(InfoUtil.deleteZeroPrefix(x.getMainOutAllocateOrderId()), order.getOuterStoOrderId()))
                                .map(OuiAllocateOrderDetailIndex::getMainReceiveOrgId).findFirst().orElse(null);
                        boolean isECommerceOrder = InfoUtil.isECommerceOrder(receiveOrgId);
                        for (ConsignmentOrderLine line : lines) {
                            if (order.getId() != null && StringUtils.isNotBlank(line.getConsignmentOrderId())
                                    && line.getConsignmentOrderId().equals(order.getId().toString())){
                                //电商调拨单
                                String key;
                                if (isECommerceOrder){
                                    key = order.getOuterStoOrderId() + "," + line.getOuterStoLineId();
                                }else {
                                    key = order.getOuterStoOrderId() + "," + line.getScItemId();
                                }
                                String outerDeliveryOrderId = map.get(key);
                                if (StringUtils.isBlank(outerDeliveryOrderId)){
                                    map.put(key,order.getOuterDeliveryOrderId());
                                }else {
                                    //如果已经有该交货单号了就不重新放进map
                                    if (StringUtils.isNotBlank(order.getOuterDeliveryOrderId()) && !outerDeliveryOrderId.contains(order.getOuterDeliveryOrderId())){
                                        map.put(key,map.get(key) + "," + order.getOuterDeliveryOrderId());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return map;

    }


    public Map<String,String> queryConsignmentOrderNumMap(List<String> codes){
        Map<String,String> consignmentOrderMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(codes)) {
            QueryConsignmentOrderByStoOrderIdsRequest queryConsignmentOrderByStoOrderIdsRequest = new QueryConsignmentOrderByStoOrderIdsRequest();
            queryConsignmentOrderByStoOrderIdsRequest.setStoOrderIds(codes);
            Result<List<ConsignmentOrder>> consignmentOrderResult = consignmentOrderService.queryConsignmentOrderByStoOrderIds(queryConsignmentOrderByStoOrderIdsRequest);
            if (Objects.nonNull(consignmentOrderResult) && CollectionUtils.isNotEmpty(consignmentOrderResult.getResult())) {
//                Map<String, List<ConsignmentOrder>> map = consignmentOrderResult.getResult().stream().
//                        collect(Collectors.groupingBy(ConsignmentOrder::getStoOrderId));
//                map.forEach((k,v)->{
//                    if (StringUtils.isNotBlank(k) && CollectionUtils.isNotEmpty(v)){
//                        List<String> collect = v.stream().map(ConsignmentOrder::getOuterDeliveryOrderId).collect(Collectors.toList());
//                    }
//                });
                for (ConsignmentOrder consignmentOrder : consignmentOrderResult.getResult()) {
                    if (!Objects.equals(consignmentOrder.getStatus(),1)){
                        continue;
                    }
                    String outerDeliveryOrderId = consignmentOrderMap.get(consignmentOrder.getStoOrderId());
                    if (StringUtils.isEmpty(outerDeliveryOrderId)){
                        consignmentOrderMap.put(consignmentOrder.getStoOrderId(),consignmentOrder.getOuterDeliveryOrderId());
                    }else{
                        if (StringUtils.isNotEmpty(consignmentOrder.getOuterDeliveryOrderId())) {
                            consignmentOrderMap.put(consignmentOrder.getStoOrderId(),
                                    consignmentOrderMap.get(consignmentOrder.getStoOrderId())+ "," + consignmentOrder.getOuterDeliveryOrderId());
                        }
                    }
                }
            }
        }
        return consignmentOrderMap;
    }

    /** 查询出入库明细 和 出库明细 使用赋值的情况 **/
    private void evalInOutResponseMaps(Set<String> allocateApplyOrderIds,
                                       Map<String,List<OutWarehouseDetailDTO>> inOutResponseMap,
                                       Map<String,GetListOutinForAllocationResponse> allocationMap){
        if (inOutResponseMap == null){
            inOutResponseMap = new HashMap<>();
        }
        if (allocationMap == null){
            allocationMap = new HashMap<>();
        }
        List<Future<GetListOutinForAllocationResponse>> futureList = Lists.newArrayList();
        for (String allocateApplyOrderId:allocateApplyOrderIds){

            CompletableFuture<GetListOutinForAllocationResponse> future = CompletableFuture.supplyAsync(() -> {
                GetListOutinForAllocationResponse inOutResponse = null;
                try {
                    AllocateOrderGetInOutOrderRequest allocateOrderGetInOutOrderRequest = new AllocateOrderGetInOutOrderRequest();
                    allocateOrderGetInOutOrderRequest.setAllocateOrderId(allocateApplyOrderId);
                    allocateOrderGetInOutOrderRequest.setStatusList(Lists.newArrayList(WmsStatusEnum.Normal.getValue()));
                    allocateOrderGetInOutOrderRequest.setSize(300);
                    log.info("inOutResponseRequest:{}", JSON.toJSONString(allocateOrderGetInOutOrderRequest));
                    inOutResponse = unifiedInventoryService.getListOutinForAllocation(allocateOrderGetInOutOrderRequest);
                    log.info("inOutResponseResult:{}",JSON.toJSONString(inOutResponse));
                } catch (Exception e) {
                    log.error("多线程查询货品异常", e);
                }
                if (null == inOutResponse) {
                    return null;
                }
                return inOutResponse;
            }, allocateApplyTaskExecutor);
            futureList.add(future);
        }

        for (Future<GetListOutinForAllocationResponse> listFuture : futureList) {
            try {
                GetListOutinForAllocationResponse inOutResponse = listFuture.get();
                String allocateOrderId = getAllocateOrderId(inOutResponse);
                if (StringUtils.isNotBlank(allocateOrderId)){
                    //用于查询物流明细
                    allocationMap.put(allocateOrderId,inOutResponse);
                }

                List<OutWarehouseDetailDTO> outDetailDTOs = getOutWarehouseDetailDTOS(inOutResponse);
                if (CollectionUtils.isNotEmpty(outDetailDTOs)) {
                    inOutResponseMap.put(outDetailDTOs.get(0).getSourceSubOrderId(), outDetailDTOs);
                }
            } catch (Exception e) {
                // 异常处理
                log.error("获取多线程查询结果异常", e);

            }
        }
    }

//    private Map<String,List<OutWarehouseDetailDTO>> getInOutResponseMap(Set<String> allocateApplyOrderIds){
//        Map<String,List<OutWarehouseDetailDTO>> inOutResponseMap = new HashMap<>();
//        List<Future<GetListOutinForAllocationResponse>> futureList = Lists.newArrayList();
//        for (String allocateApplyOrderId:allocateApplyOrderIds){
//
//            CompletableFuture<GetListOutinForAllocationResponse> future = CompletableFuture.supplyAsync(() -> {
//                GetListOutinForAllocationResponse inOutResponse = null;
//                try {
//                    AllocateOrderGetInOutOrderRequest allocateOrderGetInOutOrderRequest = new AllocateOrderGetInOutOrderRequest();
//                    allocateOrderGetInOutOrderRequest.setAllocateOrderId(allocateApplyOrderId);
//                    allocateOrderGetInOutOrderRequest.setStatusList(Lists.newArrayList(WmsStatusEnum.Normal.getValue()));
//                    allocateOrderGetInOutOrderRequest.setSize(300);
//                    log.info("inOutResponseRequest:{}", JSON.toJSONString(allocateOrderGetInOutOrderRequest));
//                    inOutResponse = unifiedInventoryService.getListOutinForAllocation(allocateOrderGetInOutOrderRequest);
//                    log.info("inOutResponseResult:{}",JSON.toJSONString(inOutResponse));
//                } catch (Exception e) {
//                    log.error("多线程查询货品异常", e);
//                }
//                if (null == inOutResponse) {
//                    return null;
//                }
//            return inOutResponse;
//            }, allocateApplyTaskExecutor);
//            futureList.add(future);
//        }
//
//        for (Future<GetListOutinForAllocationResponse> listFuture : futureList) {
//            try {
//                GetListOutinForAllocationResponse inOutResponse = listFuture.get();
//                List<OutWarehouseDetailDTO> outDetailDTOs = getOutWarehouseDetailDTOS(inOutResponse);
//                if (CollectionUtils.isNotEmpty(outDetailDTOs)) {
//                    inOutResponseMap.put(outDetailDTOs.get(0).getSourceSubOrderId(), outDetailDTOs);
//                }
//            } catch (Exception e) {
//                // 异常处理
//                log.error("获取多线程查询结果异常", e);
//
//            }
//        }
//        return inOutResponseMap;
//    }


    //2022.10.31 ... 根据外部调拨单号查询出入库单
    private Map<String,List<WmsMainOrder>> logisticsMap(Set<String> outAllocateOrderIdList){
        if (CollectionUtils.isEmpty(outAllocateOrderIdList)){
            return Maps.newHashMap();
        }
        outAllocateOrderIdList = outAllocateOrderIdList.stream().filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(outAllocateOrderIdList)){
            return Maps.newHashMap();
        }
        AllocateOrderGetWmsOrdersRequest wmsOrdersRequest = new AllocateOrderGetWmsOrdersRequest();
        wmsOrdersRequest.setOutAllocateOrderIdList(Lists.newArrayList(outAllocateOrderIdList));
        wmsOrdersRequest.setStatusList(Lists.newArrayList(WmsStatusEnum.Normal.getValue()));
        wmsOrdersRequest.setReturnFields(Lists.newArrayList("shipPhone","shipNo","orderStatus","postingTime","out_order_id","outAllocateOrderId","outSourceOrderId","sumQuantity"));
        wmsOrdersRequest.setSize(MAX_PAGE_SIZE);
        Object wmsOrders = unifiedInventoryService.getWmsOrders(wmsOrdersRequest);
        List<WmsMainOrder> wmsMainOrders = convertWmsMainOrderList(wmsOrders);
        if (CollectionUtils.isEmpty(wmsMainOrders)){
            return Maps.newHashMap();
        }
        return wmsMainOrders.stream().collect(Collectors.groupingBy(WmsMainOrder::getOutAllocateOrderId));
    }

    /** 用于物流信息 **/
    private Map<String,Object> getWmsOrders(Set<String> allocateApplyOrderIds){
//        Map<String,List<InAndOutOfWarehouseOrderDTO>> wmsOrdersMap = new HashMap<>();
        Map<String,Object> wmsOrdersMap = new HashMap<>();
        List<Future<Object>> futureList = Lists.newArrayList();
        for (String allocateApplyOrderId:allocateApplyOrderIds){
            CompletableFuture<Object> future = CompletableFuture.supplyAsync(() -> {
                Object wmsOrders = null;
                try {
                    AllocateOrderGetWmsOrdersRequest allocateOrderGetWmsOrdersRequest = new AllocateOrderGetWmsOrdersRequest();
                    allocateOrderGetWmsOrdersRequest.setAllocateOrderId(allocateApplyOrderId);
                    allocateOrderGetWmsOrdersRequest.setStatus(WmsStatusEnum.Normal.getValue());
                    allocateOrderGetWmsOrdersRequest.setSize(300);
                    log.info("inOutResponseRequest:{}", JSON.toJSONString(allocateOrderGetWmsOrdersRequest));
                    wmsOrders = unifiedInventoryService.getWmsOrders(allocateOrderGetWmsOrdersRequest);
                    log.info("inOutResponseResult:{}",JSON.toJSONString(wmsOrders));
                } catch (Exception e) {
                    log.error("多线程查询货品异常", e);
                }
                if (null == wmsOrders) {
                    return null;
                }
                return wmsOrders;
            }, allocateApplyTaskExecutor);
            futureList.add(future);
        }

        for (Future<Object> listFuture : futureList) {
            try {
                Object wmsOrders = listFuture.get();
                String allocateOrderId = getAllocateOrderIdByWmsOrder(wmsOrders);
                if (StringUtils.isNotBlank(allocateOrderId)){
                    wmsOrdersMap.put(allocateOrderId,wmsOrders);
                }
//                List<InAndOutOfWarehouseOrderDTO> inAndOutOfWarehouseOrderDTOS =  getInAndOutOfWarehouseOrderDTOS(wmsOrders);
//                if (CollectionUtils.isNotEmpty(inAndOutOfWarehouseOrderDTOS)) {
//                    wmsOrdersMap.put(inAndOutOfWarehouseOrderDTOS.get(0).getSourceWarehousingOrderId(), inAndOutOfWarehouseOrderDTOS);
//                }
            } catch (Exception e) {
                // 异常处理
                log.error("获取多线程查询结果异常", e);

            }
        }
        return wmsOrdersMap;
    }

//    private Map<String,List<InAndOutOfWarehouseOrderDTO>> getWmsOrders(Set<String> allocateApplyOrderIds){
//        Map<String,List<InAndOutOfWarehouseOrderDTO>> wmsOrdersMap = new HashMap<>();
//        List<Future<Object>> futureList = Lists.newArrayList();
//        for (String allocateApplyOrderId:allocateApplyOrderIds){
//            CompletableFuture<Object> future = CompletableFuture.supplyAsync(() -> {
//                Object wmsOrders = null;
//                try {
//                    AllocateOrderGetWmsOrdersRequest allocateOrderGetWmsOrdersRequest = new AllocateOrderGetWmsOrdersRequest();
//                    allocateOrderGetWmsOrdersRequest.setAllocateOrderId(allocateApplyOrderId);
//                    allocateOrderGetWmsOrdersRequest.setStatus(WmsStatusEnum.Normal.getValue());
//                    allocateOrderGetWmsOrdersRequest.setSize(300);
//                    log.info("inOutResponseRequest:{}", JSON.toJSONString(allocateOrderGetWmsOrdersRequest));
//                    wmsOrders = unifiedInventoryService.getWmsOrders(allocateOrderGetWmsOrdersRequest);
//                    log.info("inOutResponseResult:{}",JSON.toJSONString(wmsOrders));
//                } catch (Exception e) {
//                    log.error("多线程查询货品异常", e);
//                }
//                if (null == wmsOrders) {
//                    return null;
//                }
//                return wmsOrders;
//            }, allocateApplyTaskExecutor);
//            futureList.add(future);
//        }
//
//        for (Future<Object> listFuture : futureList) {
//            try {
//                Object wmsOrders = listFuture.get();
//                List<InAndOutOfWarehouseOrderDTO> inAndOutOfWarehouseOrderDTOS =  getInAndOutOfWarehouseOrderDTOS(wmsOrders);
//                if (CollectionUtils.isNotEmpty(inAndOutOfWarehouseOrderDTOS)) {
//                    wmsOrdersMap.put(inAndOutOfWarehouseOrderDTOS.get(0).getSourceWarehousingOrderId(), inAndOutOfWarehouseOrderDTOS);
//                }
//            } catch (Exception e) {
//                // 异常处理
//                log.error("获取多线程查询结果异常", e);
//
//            }
//        }
//        return wmsOrdersMap;
//    }
    /**
     * 调拨单列表 ES搜索
     * @param request
     * @return
     */
    public Result<List<AllocateOrderDetailVO>> searchES(AllocateOrderDetailSearchRequest request){
        //获取ES结果
//        AllocateOrderDetailSearchRequest searchRequest = new AllocateOrderDetailSearchRequest();
        //处理时间参数
        StopWatch stopWatch = new StopWatch();
        handleSearchConditions(request);
//        Map<String, String> wmsMap1 = InfoUtil.getWmsMap(null);
//        Result<List<OuiAllocateOrderDetailIndex>> result = detailIndexService.search(request);
        stopWatch.start("searchES-get");
        Result<List<OuiAllocateOrderDetailIndex>> result = detailIndexService.get(request);
        stopWatch.stop();
        stopWatch.start("searchES-getCount");
        Result<Long> count = detailIndexService.getCount(request);
        stopWatch.stop();
        List<AllocateOrderDetailVO> detailVOS = Lists.newArrayList();
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())){
            Set<String> subAllocateOrderIds = new HashSet<>();
            //预报单id
            Set<String> allocateApplyOrderIds = new HashSet<>();

            //调拨单id
            // Set<String> stoOrderIds = new HashSet<>();
            Set<String> outStoOrderIds = new HashSet<>();
            for (OuiAllocateOrderDetailIndex index : result.getResult()) {
                if (StringUtils.isNotEmpty(index.getMainAllocateApplyOrderId())){
                    allocateApplyOrderIds.add(index.getMainAllocateApplyOrderId());
                }
                // stoOrderIds.add(index.getMainCode());
                outStoOrderIds.add(index.getMainOutAllocateOrderId());
                subAllocateOrderIds.add(String.valueOf(index.getSubAllocateOrderId()));
            }

            //客户、客户地址数据，做成弱依赖
            Map<String,String> orgMap =Maps.newHashMap();
            stopWatch.start("searchES-getOrgMap");
            try {
                orgMap = getOrgMap(result);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getOrgMapInfo error", e);
            }
            stopWatch.stop();
            //仓库
            Map<String,WmsSDO> wmsMap = Maps.newHashMap();
            stopWatch.start("searchES-getWmsMap");
            try {
                wmsMap = getWmsMap(result);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getWmsMapInfo error", e);
            }
            stopWatch.stop();
            //客户 addressCode->customer
            Map<String, AllocateOrderGetCustomerResponse> customerResponseMap = Maps.newHashMap();
            stopWatch.start("searchES-getCustomerResponseMap");
            try {
                customerResponseMap = getCustomerResponseMap(result);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getCustomerInfo error", e);
            }
            stopWatch.stop();
            //客户 customerCode -> customer
            Map<String, AllocateOrderGetCustomerResponse> customerCodeMap = Maps.newHashMap();
            stopWatch.start("searchES-getCustomerMapByCustomerCodeFromMap");
            try {
                customerCodeMap = getCustomerMapByCustomerCodeFromMap(customerResponseMap);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getCustomerCodeInfo error", e);
            }
            stopWatch.stop();
            //branchCustomerCodeMap
            Map<String, AllocateOrderGetCustomerResponse> branchCustomerMap = Maps.newHashMap();
            stopWatch.start("searchES-getBranchCustomerMap");
            try {
                branchCustomerMap = getBranchCustomerMap(result);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getBranchCustomerInfo error", e);
            }
            stopWatch.stop();
            //商品
            Map<String,AllocateOrderDetailBatchGetScItemResponse> scItemResponseMap = Maps.newHashMap();
            stopWatch.start("searchES-getScItemResponseMap");
            try {
                scItemResponseMap = getScItemResponseMap(result);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getScItemInfo error", e);
            }
            stopWatch.stop();
            //出入库单明细
            Map<String,List<OutWarehouseDetailDTO>> inOutResponseMap = Maps.newHashMap();
            //出入库明细response
            Map<String,GetListOutinForAllocationResponse> allocationMap = Maps.newHashMap();
            stopWatch.start("searchES-evalInOutResponseMaps");
            try {
//                inOutResponseMap = getInOutResponseMap(subAllocateOrderIds);
                evalInOutResponseMaps(subAllocateOrderIds,inOutResponseMap,allocationMap);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getInOutInfo error", e);
            }
            stopWatch.stop();
            //出库单
//            Map<String,List<InAndOutOfWarehouseOrderDTO>> wmsOrdersMap = Maps.newHashMap();
            //存放出入库单用于后期查询
            Map<String,Object> wmsOrdersMap = Maps.newHashMap();
            stopWatch.start("searchES-getWmsOrders");
            try {
                wmsOrdersMap = getWmsOrders(subAllocateOrderIds);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getWmsOrderInfo error", e);
            }
            stopWatch.stop();
            // 获取物料凭证上的车牌电话
            Map<String,List<WmsMainOrder>> logisticsMap = Maps.newHashMap();
            stopWatch.start("searchES-logisticsMap");
            try{
                logisticsMap = logisticsMap(outStoOrderIds);
            }catch (Throwable e){
                log.error("AllocateOrderReadServiceImpl_logisticsMap_error",e);
            }
            stopWatch.stop();
            //预报单
            stopWatch.start("searchES-queryAllocateApplyOrderMap");
            Map<String,AllocateApplyOrder> allocateApplyOrderMap = queryAllocateApplyOrderMap(new ArrayList<>(allocateApplyOrderIds));
            stopWatch.stop();
            //预报单明细
            stopWatch.start("searchES-queryAllocateApplyOrderDetailMap");
            Map<String,List<AllocateApplyOrderDetail>> stringAllocateApplyOrderDetailMap = queryAllocateApplyOrderDetailMap(Lists.newArrayList(allocateApplyOrderIds));
            stopWatch.stop();
            //交货单
//            Map<String, String> consignmentOrderMap = queryConsignmentOrderNumMap(new ArrayList<>(stoOrderIds));
//            Map<String,String> consignmentOrderMap = getConsignmentOrderMap(Lists.newArrayList(outStoOrderIds));
            stopWatch.start("searchES-getConsignmentOrderMapWithIsECommerceOrder");
            Map<String,String> consignmentOrderMap = getConsignmentOrderMapWithIsECommerceOrder(result.getResult());
            stopWatch.stop();
            for (OuiAllocateOrderDetailIndex index : result.getResult()) {
                AllocateOrderDetailVO detailVO = new AllocateOrderDetailVO();
                BeanUtils.copyProperties(index, detailVO);
               // detailVO.setMainBusinessScenario(index.getMainBusinessScenario());
                detailVO.setType(index.getSubType()==null?null:index.getSubType().intValue());
                detailVO.setTypeDesc(InfoUtil.getTypeDesc(index.getSubType()==null?null:index.getSubType().intValue()));
                detailVO.setCode(index.getMainCode());
                //外部单号，判断牛要客id字段是否有值，如果有值用牛要客字段的值，如果没有取外部单号的值
                detailVO.setOutAllocateOrderId(StringUtils.isNotBlank(index.getMainNykId())?index.getMainNykId():index.getMainOutAllocateOrderId());
                detailVO.setAllocateApplyOrderCode(index.getMainAllocateApplyOrderCode());
                detailVO.setLineNo(index.getSubLineNo() == null?null:index.getSubLineNo().toString());
                detailVO.setOutAllocateOrderLineId(index.getSubOutAllocateOrderLineId());
                detailVO.setAllocateApplyOrderLineId(index.getSubAllocateApplyOrderLineId());
                detailVO.setApplyOrgId(index.getMainApplyOrgId());
                //是否电商调拨单
                boolean isECommerceOrder = InfoUtil.isECommerceOrder(index.getMainReceiveOrgId());
                //TODO 看是否冗余
                // TODO: 2021/12/2 余红伟，不要写魔法变量，货品组是固定的11？如果是其他货品组？
                detailVO.setApplyOrgName(orgMap.get(index.getMainApplyOrgId()));
                detailVO.setProductGroup("11");
                detailVO.setProductGroupDesc("常温");
                detailVO.setStatus(index.getMainStatus()==null?null:index.getMainStatus().intValue());
                detailVO.setStatusDesc(InfoUtil.getStatusEpochDesc(index.getMainStatus()==null?null:index.getMainStatus().intValue()));
                detailVO.setStatusStr(InfoUtil.getStatusDesc(index.getMainStatus()==null?null:index.getMainStatus().intValue()));
                detailVO.setIsDTC(Objects.equals(index.getMainIsDTC(), 1L));
                detailVO.setIsDTCDesc(Objects.equals(index.getMainIsDTC(),1L)?"是":"否");
                detailVO.setReturnOrder(InfoUtil.getBoolean(index.getMainReturnOrder()));
                detailVO.setReturnOrderDesc(InfoUtil.getBooleanDesc(index.getMainReturnOrder()));
                // 仓库 收发组织
                detailVO.setReceiveAreaId(index.getMainReceiveAreaId());
                WmsSDO receiveWmsSDO = wmsMap.get(index.getMainReceiveAreaId());
                if (receiveWmsSDO != null){
                    detailVO.setReceiveAreaName(receiveWmsSDO.getName());
                    detailVO.setReceiveFactoryCode(receiveWmsSDO.getFactoryCode());
                    detailVO.setReceiveInventoryCode(receiveWmsSDO.getInventoryCode());
                    detailVO.setReceiveAreaCode(receiveWmsSDO.getCode());
                }
                WmsSDO receiveWarehouseWmsSDO =  wmsMap.get(index.getMainReceiveWarehouseId());
                if (receiveWarehouseWmsSDO != null){
                    detailVO.setReceiveWarehouseName(receiveWarehouseWmsSDO.getName());
                    //收货物理仓编码
                    detailVO.setReceiveWarehouseCode(receiveWarehouseWmsSDO.getCode());
                }
                detailVO.setReceiveOrgId(index.getMainReceiveOrgId());
                detailVO.setReceiveOrgName(orgMap.get(index.getMainReceiveOrgId()));
                detailVO.setShipAreaId(index.getMainShipAreaId());
                detailVO.setShipOrgId(index.getMainShipOrgId());
                detailVO.setShipOrgName(orgMap.get(index.getMainShipOrgId()));
                WmsSDO shipWmsSDO = wmsMap.get(index.getMainShipAreaId());
                if (shipWmsSDO != null){
                    detailVO.setShipAreaName(shipWmsSDO.getName());
                    detailVO.setShipFactoryCode(shipWmsSDO.getFactoryCode());
                    detailVO.setShipInventoryCode(shipWmsSDO.getInventoryCode());
                    detailVO.setShipAreaCode(shipWmsSDO.getCode());
                }
                WmsSDO shipWarehouseWmsSDO = wmsMap.get(index.getMainShipWarehouseId());
                if (shipWarehouseWmsSDO != null){
                    detailVO.setShipWarehouseName(shipWarehouseWmsSDO.getName());
                    detailVO.setShipWarehouseCode(shipWarehouseWmsSDO.getCode());
                }
                // 客户编码
                detailVO.setCustomer(index.getMainCustomer());
                //TO
                AllocateOrderGetCustomerResponse customerResponse = customerResponseMap.get(index.getMainAddressCode());
                if (customerResponse != null){
                    detailVO.setCustomerName(customerResponse.getCustomerName());
                    detailVO.setCustomerAddress(customerResponse.getCustomerAddress());
                    detailVO.setCustomerAddressName(customerResponse.getCustomerAddressName());
                    detailVO.setReceiver(customerResponse.getReceiver());
                    detailVO.setContactNumber(customerResponse.getContactNumber());
                }
                //TODO 物流信息
                detailVO.setLogisticsInfo(null);
                //如果状态是关闭的, 且发货数量 > 0(已关闭,部分发货) 或收货数量 > 0(已关闭,部分收货), 理论上全部发货关闭不了
                if (AllocateOrderStatus.CLOSED.getValue().equals(index.getSubStatus()==null?null:index.getSubStatus().intValue())){
                    if (index.getSubReceiveQuantity() != null && index.getSubReceiveQuantity() > 0){
                        detailVO.setLineStatusDesc(InfoUtil.getStatusEpochDesc(AllocateOrderStatus.CLOSED_AND_PARTRECEIVED.getValue()));
                    }else if (index.getSubShipQuantity() != null && index.getSubShipQuantity() > 0){
                        detailVO.setLineStatusDesc(InfoUtil.getStatusEpochDesc(AllocateOrderStatus.CLOSED_AND_PARTSHIPPED.getValue()));
                    }else {
                        detailVO.setLineStatusDesc(InfoUtil.getStatusEpochDesc(AllocateOrderStatus.CLOSED.getValue()));
                    }
                }else {
                    detailVO.setLineStatusDesc(InfoUtil.getStatusEpochDesc(index.getSubStatus()==null?
                            null:index.getSubStatus().intValue()));
                }

                //如果状态是关闭的, 且发货数量 > 0(已关闭,部分发货) 或收货数量 > 0(已关闭,部分收货), 理论上全部发货关闭不了
                if (AllocateOrderStatus.CLOSED.getValue().equals(index.getSubStatus()==null?null:index.getSubStatus().intValue())){
                    if (index.getSubReceiveQuantity() != null && index.getSubReceiveQuantity() > 0){
                        detailVO.setLineStatusStr(InfoUtil.getStatusDesc(AllocateOrderStatus.CLOSED_AND_PARTRECEIVED.getValue()));
                    }else if (index.getSubShipQuantity() != null && index.getSubShipQuantity() > 0){
                        detailVO.setLineStatusStr(InfoUtil.getStatusDesc(AllocateOrderStatus.CLOSED_AND_PARTSHIPPED.getValue()));
                    }else {
                        detailVO.setLineStatusStr(InfoUtil.getStatusDesc(AllocateOrderStatus.CLOSED.getValue()));
                    }
                }else {
                    detailVO.setLineStatusStr(InfoUtil.getStatusDesc(index.getSubStatus()==null?null:index.getSubStatus().intValue()));
                }
//                detailVO.setStatus(index.getMainStatus()==null?null:index.getMainStatus().intValue());
//                detailVO.setStatusDesc(InfoUtil.getStatusEpochDesc(detailVO.getStatus()));

                detailVO.setScItemId(index.getSubScItemId());
                detailVO.setScItemCode(index.getSubScItemCode());
                AllocateOrderDetailBatchGetScItemResponse scItemResponse = scItemResponseMap.get(index.getSubScItemId());
                if (scItemResponse != null){
                    detailVO.setScItemName(scItemResponse.getTitle());
                    if (StringUtils.isBlank(detailVO.getScItemCode())){
                        detailVO.setScItemCode(scItemResponse.getScItemCode());
                    }
                }
                detailVO.setShipMethodDesc(InfoUtil.getShipMethodDesc(index.getMainShipMethod() == null?null:
                        index.getMainShipMethod().intValue()));
                detailVO.setQuantity(InfoUtil.handleQuantityDate(index.getSubQuantity()));
                if (Objects.equals(Boolean.TRUE,InfoUtil.getBoolean(index.getMainReturnOrder()))){
                    detailVO.setConfirmQuantity(InfoUtil.handleQuantityDate(index.getSubQuantity()));
                }else {
                    detailVO.setConfirmQuantity(InfoUtil.handleQuantityDate(index.getSubConfirmQuantity()));
                }
                //  交货数量 取值交货单更新
                detailVO.setDeliveryQuantity(index.getSubDeliveryQuantity());
                detailVO.setShipQuantity(index.getSubShipQuantity()==null?null:index.getSubShipQuantity().toString());
                //es没有收货数量
                detailVO.setReceiveQuantity(index.getSubReceiveQuantity()==null?null:index.getSubReceiveQuantity().toString());
                detailVO.setNotIssuedQuantity(InfoUtil.handleQuantityDate(InfoUtil.subtract(index.getSubQuantity(),index.getSubShipQuantity())));
                //退单在途数量=0；
                if (Objects.equals(Boolean.TRUE,InfoUtil.getBoolean(index.getMainReturnOrder()))){
                    detailVO.setTransQuantity("0");
                }else {
                    detailVO.setTransQuantity(InfoUtil.subtract(index.getSubShipQuantity(),index.getSubReceiveQuantity()));
                }
                //es没有赠送数量
                detailVO.setGiftQuantity(index.getSubGiftQuantity());
                detailVO.setUnit(index.getSubUnit());
                detailVO.setPrice(index.getSubPrice());
                detailVO.setDiscountPrice(InfoUtil.getDiscountPrice(index.getSubSubTotalAmount(),index.getSubQuantity()));
                detailVO.setAmount(InfoUtil.multiply(index.getSubPrice(),index.getSubQuantity()));
                //结算金额
                detailVO.setCrossCompanySettlement(index.getSubExchangeAmt());
                //这个地方得保证 折后金额和小计金额的一致性.
                detailVO.setDiscountAmt(index.getSubDiscountAmount());
                //TODO 交货金额哪里来.
                detailVO.setDeliveryAmt(InfoUtil.multiply(index.getSubPrice(),index.getSubDeliveryQuantity()));
                detailVO.setDeliveryDiscountAmt(InfoUtil.multiply(detailVO.getDiscountPrice(),index.getSubDeliveryQuantity()));
                detailVO.setShippedDiscountAmt(InfoUtil.multiply(index.getSubShipQuantity() ==null?null:index.getSubShipQuantity().toString(),detailVO.getDiscountPrice()));;
                detailVO.setShippedAmt(InfoUtil.multiply(index.getSubShipQuantity()==null?null:index.getSubShipQuantity().toString(),index.getSubPrice()));
                detailVO.setTaxRate(index.getSubTaxRate());
                detailVO.setExpectedProductDate(TimeUtil.getDateByLong(index.getSubExpectedProduceDate()));
                detailVO.setExpectedProductDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getExpectedProductDate()));
                detailVO.setExpectedDeliveryDate(TimeUtil.getDateByLong(index.getMainExpectedDeliveryDate()));
                detailVO.setExpectedDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getExpectedDeliveryDate()));
                detailVO.setLineExpectedDeliveryDate(TimeUtil.getDateByLong(index.getSubExpectedDeliveryDate()));
                detailVO.setLineExpectedDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getLineExpectedDeliveryDate()));
                detailVO.setSendBackRequired(InfoUtil.getBoolean(index.getMainSendBackRequired()));
                detailVO.setSendBackRequiredDesc(InfoUtil.getBooleanDesc(index.getMainSendBackRequired()));
                detailVO.setCloseReason(index.getSubCloseReason());
                detailVO.setCloseDesc(InfoUtil.getBooleanDesc(index.getSubClose()));
                detailVO.setClosed(InfoUtil.getBoolean(index.getSubClose()));
                detailVO.setLineRemark(index.getSubRemarks());
                // TODO 这个和期待生产日期的区别  暂时没有
                detailVO.setProductDate(TimeUtil.getDateByLong(index.getSubExpectedProduceDate()));
                detailVO.setProductDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getProductDate()));
                //TODO 出库生产日期是  出入库单的生产日期 多值 逗号
                detailVO.setOutWarehouseProductDate(null);
                //时间直接使用gmt了.
//                detailVO.setCreateTime(index.getMainCreateTime()==null?InfoUtil.getDate(index.getMainGmtCreate()):InfoUtil.getDate(index.getMainCreateTime()));
                detailVO.setCreateTime(InfoUtil.getDate(index.getMainGmtCreate()));
                detailVO.setSubCreateTime(InfoUtil.getDate(index.getSubGmtCreate()));
                //确认日期是 确认数量变化的时间 sap找sap 回复创建调拨单时间
                detailVO.setConfirmDate(TimeUtil.getIgnoreNullDateByLong(index.getSubConfirmTime()));
                detailVO.setConfirmDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getConfirmDate()));
                // 交货日期
                if (index.getSubDeliveryDate()!= null && index.getSubDeliveryDate() == new Date(0).getTime()){
                    detailVO.setDeliveryDate(null);
                }else {
                    detailVO.setDeliveryDate(TimeUtil.getDateByLong(index.getSubDeliveryDate()));
                }
//                detailVO.setDeliveryDate(TimeUtil.getDateByLong(index.getSubDeliveryDate()));
                detailVO.setDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getDeliveryDate()));
                //TODO 出库日期 ? 发货时间
                detailVO.setShipTime(TimeUtil.getIgnoreNullDateByLong(index.getSubShipTime()));
                detailVO.setShipTimeStr(TimeUtil.formatYYYY_MM_dd(detailVO.getShipTime()));
                detailVO.setOutWarehouseDate(null);
//                detailVO.setReceiveDate(null);
                detailVO.setReceiveTime(TimeUtil.getIgnoreNullDateByLong(index.getSubReceiveTime()));
                detailVO.setReceiveTimeStr(TimeUtil.formatYYYY_MM_dd(detailVO.getReceiveTime()));
                if (receiveWarehouseWmsSDO != null){
                    detailVO.setReceiveAreaContactor(receiveWarehouseWmsSDO.getContactPerson());
                    detailVO.setReceiveAreaPhone(receiveWarehouseWmsSDO.getPhone());
                    detailVO.setReceiveAreaAddress(receiveWarehouseWmsSDO.getAddress());
                }
                //TODO 单据日期的写入 需要再看
                detailVO.setDocDate(InfoUtil.getDate(index.getMainDocDate()));
                detailVO.setDocDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getDocDate()));
                //TODO 生效日期
                detailVO.setBeginDate(null);
                detailVO.setLineExpectedDeliveryDate(InfoUtil.getDate(index.getSubExpectedDeliveryDate()));
                detailVO.setLineExpectedDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getLineExpectedDeliveryDate()));
//                detailVO.setCreator(NameUtil.getRealName(index.getMainCreator()));

                //detailVO.setCreator(InfoUtil.getRealName(index.getMainCreator()));
                detailVO.setCreator(InfoUtil.getRealName(index.getSubCreator()));
                detailVO.setCreateTime(InfoUtil.getDate(index.getMainGmtCreate()));
                //detailVO.setCreateTime(InfoUtil.getDate(index.getSubGmtCreate()));
                //TODO 提交时间
                detailVO.setSubmitTime(InfoUtil.getDate(index.getMainSubmitTime()));
//                detailVO.setUpdator(NameUtil.getRealName(index.getMainUpdater()));
                detailVO.setUpdator(InfoUtil.getRealName(index.getMainUpdater()));
                detailVO.setUpdateTime(InfoUtil.getDate(index.getMainGmtModified()));
                detailVO.setRemark(index.getMainRemark());
                detailVO.setOrderReasonDesc(EnumUtils.getOrderReason(index.getMainOrderReason()));
                //判断仓库是否有值
                if(Objects.nonNull(receiveWmsSDO)) {
                    detailVO.setSapInternalSalesBPCode(receiveWmsSDO.getSapInternalSalesBPCode());
                    detailVO.setSapInternalDeliveryBPCode(receiveWmsSDO.getSapInternalDeliveryBPCode());
                    detailVO.setSapSalesBPCode(receiveWmsSDO.getSapSalesBPCode());
                    detailVO.setSapDeliveryBPCode(receiveWmsSDO.getSapDeliveryBPCode());
                    if (Objects.equals(index.getMainType()==null?null:index.getMainType().intValue(),
                            AllocateOrderTypeEnum.HEADQUARTER_SALES.getType())){
                        detailVO.setSapCustomer(receiveWmsSDO.getSapSalesBPCode());
                        detailVO.setSapCustomerAddress(receiveWmsSDO.getSapDeliveryBPCode());
                    }
                }
                //详细地址
                if ( receiveWarehouseWmsSDO != null && StringUtils.isNotBlank(receiveWarehouseWmsSDO.getAddress())
                        && Objects.equals(index.getMainType()==null?null:index.getMainType().intValue(),
                        AllocateOrderTypeEnum.HEADQUARTER_SALES.getType())){
                    detailVO.setSapCustomerAddress( receiveWarehouseWmsSDO.getAddress());
                }


                detailVO.setSapCostCenter(index.getMainSapCostCenter());
                detailVO.setSapRefPoNo(index.getMainSapRefPoNo());
                detailVO.setSapSalesOrgId(index.getMainSapSalesOrgId());
                detailVO.setSapChannel(index.getMainSapChannel());
                detailVO.setUnit(InfoUtil.convertUnit(index.getSubUnit()));
                detailVO.setMessage(index.getMainMessage());
                detailVO.setBranchCustomersCode(index.getMainBranchCustomersCode());


                //外部调拨预报单号
                AllocateApplyOrder allocateApplyOrder = allocateApplyOrderMap.get(index.getMainAllocateApplyOrderId());
                if (Objects.nonNull(allocateApplyOrder)){
                    detailVO.setOutAllocateApplyOrderId(allocateApplyOrder.getOutAllocateApplyOrderId());
                }
                List<AllocateApplyOrderDetail> allocateApplyOrderDetails = stringAllocateApplyOrderDetailMap.get(index.getMainAllocateApplyOrderId());
                if (CollectionUtils.isNotEmpty(allocateApplyOrderDetails)){
                    long sum = allocateApplyOrderDetails.stream().filter(x -> Objects.equals(x.getGoodsId(), index.getSubScItemId()) && x.getApplyQuantity() != null).mapToLong(AllocateApplyOrderDetail::getApplyQuantity).sum();
                    detailVO.setApplyQuantity(String.valueOf(sum));
                }
                //交货单号
//                if (StringUtils.isNotEmpty(detailVO.getCode())){
//                    detailVO.setDeliveryOrderNo(consignmentOrderMap.get(detailVO.getCode()));
//                }
                //电商调拨单 使用行号匹配交货单
                if (isECommerceOrder){
                    if (StringUtils.isNoneBlank(detailVO.getOutAllocateOrderId(),detailVO.getOutAllocateOrderLineId())){
                        detailVO.setDeliveryOrderNo(consignmentOrderMap.get(InfoUtil.deleteZeroPrefix(detailVO.getOutAllocateOrderId()) + "," + InfoUtil.deleteZeroPrefix(detailVO.getOutAllocateOrderLineId())));
                    }
                }else {
                    if (StringUtils.isNoneBlank(detailVO.getCode(),detailVO.getScItemId())){
                        detailVO.setDeliveryOrderNo(consignmentOrderMap.get(InfoUtil.deleteZeroPrefix(detailVO.getOutAllocateOrderId()) + "," + detailVO.getScItemId()));
                    }
                }

                //确认未发货数量 确认未发量】=确认数量 confirmQuantity-收货数量 receiveQuantity-在途数量 transQuantity
                if (StringUtils.isNotEmpty(detailVO.getConfirmQuantity())){
                    int receiveQuantity = 0;
                    int transQuantity = 0;
                    if (StringUtils.isNotEmpty(detailVO.getReceiveQuantity())){
                        receiveQuantity = Integer.parseInt(detailVO.getReceiveQuantity());
                    }
                    if (StringUtils.isNotEmpty(detailVO.getTransQuantity())){
                        transQuantity = Integer.parseInt(detailVO.getTransQuantity());
                    }
                    int confirmQuantity  = Integer.parseInt(detailVO.getConfirmQuantity())-receiveQuantity-transQuantity;
                    detailVO.setConfirmUndeliveredQuantity(Integer.toString(confirmQuantity));
                }
                //未确认数量 未确认数量=订单数量 quantity -确认数量 confirmQuantity
                if (StringUtils.isNotEmpty(detailVO.getQuantity())){
                    int confirmQuantity = 0;
                    if (StringUtils.isNotEmpty(detailVO.getConfirmQuantity())){
                        confirmQuantity = Integer.parseInt(detailVO.getConfirmQuantity());
                    }
                    int unconfirmedQuantity  = Integer.parseInt(detailVO.getQuantity())-confirmQuantity;
                    detailVO.setUnconfirmedQuantity(Integer.toString(unconfirmedQuantity));
                }


                AllocateOrderGetCustomerResponse branch = branchCustomerMap.get(index.getMainBranchCustomersCode());
                if (branch != null){
                    detailVO.setBranchCustomersName(branch.getCustomerName());
                }
//                if (StringUtils.isNotBlank(index.getMainBranchCustomersCode())){
//                    AllocateOrderGetCustomerResponse customer = InfoUtil.getCustomer(index.getMainBranchCustomersCode());
//                    if (customer != null){
//                        detailVO.setBranchCustomersName(customer.getCustomerName());
//                    }
//                }
//                detailVO.setBranchCustomersName();
//                if (StringUtils.isNotBlank(index.getMainBranchCustomersCode())){
//                    AllocateOrderGetCustomerResponse branch = customerCodeMap.get(index.getMainBranchCustomersCode());
//                    if (branch != null){
//                        detailVO.setBranchCustomersName(branch.getCustomerName());
//                    }
//                }
                //2022.05.19 填入送达方 用于对账
                detailVO.setAddressCode(index.getMainAddressCode());

//                //TODO 总部客户详细地址 来自客户接口
//                if (receiveWmsSDO != null){
//                    AllocateOrderGetCustomerResponse customerCodeResponse = customerCodeMap.get(receiveWmsSDO.getSapSalesBPCode());
//                    if (customerCodeResponse != null){
//                        detailVO.setSapCustomerAddressName(customerCodeResponse.getCustomerAddressName());
//                    }
//                }
                if (receiveWarehouseWmsSDO != null &&
                        StringUtils.isNotBlank(receiveWarehouseWmsSDO.getAddress()) &&
                        Objects.equals(index.getMainType()==null?null:index.getMainType().intValue(),
                                AllocateOrderTypeEnum.HEADQUARTER_SALES.getType().intValue())){
                    detailVO.setSapCustomerAddressName(receiveWarehouseWmsSDO.getAddress());
                }

                //这个是出入明细
//                List<InWarehouseDetailDTO> inDetailDTOs = getInWarehouseDetailDTOS(inOutResponse);
                List<OutWarehouseDetailDTO> outDetailDTOs = inOutResponseMap.get(index.getSubAllocateOrderId());
                log.info("出入库明细:" + JSON.toJSONString(outDetailDTOs));
                if (CollectionUtils.isNotEmpty(outDetailDTOs)){
                    List<OutWarehouseDetailDTO> out = outDetailDTOs.stream().filter(Objects::nonNull)
                            .filter(x -> Objects.equals(x.getScItemId(), index.getSubScItemId()))
                            .collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(out)){
                        List<String> outProductDates = out.stream().filter(x->StringUtils.isNotBlank(x.getProductionDate()))
                                .map(OutWarehouseDetailDTO::getProductionDate)
                                .map(TimeUtil::getYYYYMMddFromTimeFormat).filter(Objects::nonNull)
                                .distinct().collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(outProductDates)){
                            detailVO.setOutWarehouseProductDateDesc(StringUtils.join(outProductDates,","));
                        }
//                       detailVO.setOutWarehouseDateDesc(out.get(0).getOutWarehouseTime());
                        detailVO.setOutWarehouseDate(out.get(0).getOutWarehouseTime());
                    }
                }

                //出入库单的 物流信息
//                List<InAndOutOfWarehouseOrderDTO> inAndOutOfWarehouseOrderDTOS = wmsOrdersMap.get(index.getSubAllocateOrderId());
//                log.info("出入库单:" + JSON.toJSONString(inAndOutOfWarehouseOrderDTOS));
//                if (CollectionUtils.isNotEmpty(inAndOutOfWarehouseOrderDTOS)){
                Object wmsOrder = wmsOrdersMap.get(index.getSubAllocateOrderId());
                if (wmsOrder != null){
                    //设置下出库日期
                    //采用读取的问题
                    if (!StringUtils.isAnyBlank(detailVO.getCode(),detailVO.getScItemId())){
//                        List<AllocateOrderLogisticsInfoResponse> logisticsInfo = getLogisticsInfo(detailVO.getCode(), detailVO.getScItemId());
                        GetListOutinForAllocationResponse forAllocationResponse = allocationMap.get(index.getSubAllocateOrderId());
                        Object wms = wmsOrdersMap.get(index.getSubAllocateOrderId());
                        List<AllocateOrderLogisticsInfoResponse> logisticsInfo = getLogisticsInfo(forAllocationResponse,wms, detailVO.getScItemId());
                        log.info("logisticsInfo:{}",JSON.toJSONString(log));
                        if (CollectionUtils.isNotEmpty(logisticsInfo)){
                            List<String> collect = logisticsInfo.stream().filter(Objects::nonNull)
                                    .filter(x-> StringUtils.isNotBlank(x.getCarNo()))
                                    .map(AllocateOrderLogisticsInfoResponse::getCarNo)
                                    .distinct()
                                    .collect(Collectors.toList());
                            if (CollectionUtils.isNotEmpty(collect)){
                                detailVO.setLogisticsInfo(StringUtils.join(collect,","));
                            }
                        }

                    }
//                    if (CollectionUtils.isNotEmpty(collect)){
//                        detailVO.setLogisticsInfo(StringUtils.join(collect,","));
//                    }
                }
                //车牌  和电话号码
                if (logisticsMap != null && !logisticsMap.isEmpty() && StringUtils.isNotBlank(detailVO.getOutAllocateOrderId())){
                    List<WmsMainOrder> wmsMainOrders = logisticsMap.get(detailVO.getOutAllocateOrderId());
                    if (CollectionUtils.isNotEmpty(wmsMainOrders)){
                        String shipNos = wmsMainOrders.stream().map(WmsMainOrder::getShipNo).filter(StringUtils::isNotBlank)
                                .distinct().collect(Collectors.joining(","));
                        String shipPhones = wmsMainOrders.stream().map(WmsMainOrder::getShipPhone).filter(StringUtils::isNotBlank)
                                .distinct().collect(Collectors.joining(","));
                        detailVO.setShipNo(shipNos);
                        detailVO.setShipPhone(shipPhones);
                    }
                }
                //2023.5.21系统来源和业态
                detailVO.setFromSys(index.getMainFromSys());
                detailVO.setBusinessType(index.getMainBusinessType());
                //sap信贷校验
                detailVO.setCreditCheck(index.getMainCreditCheck());
                //sap信贷校验状态
                detailVO.setCreditCheckStatus(index.getMainCreditCheckStatus());

                //关联单号
                detailVO.setRelatedAllocateOrderCode(index.getMainRelatedAllocateOrderCode());
                //履约方式
                detailVO.setFulfillmentTypeCode(index.getMainFulfillmentTypeCode());
                //履约优先级
                detailVO.setPriority(index.getMainPriority());
                //订单标签
                detailVO.setOrderTag(index.getMainOrderTag());
                //自动履约
                detailVO.setAutoFulfillment(index.getMainAutoFulfillment());
                detailVO.setThirdDetailLineNo(index.getSubThirdLineNo());
                detailVO.setOutDetailLineNo(index.getSubOutAllocateOrderLineId());
                //预报单行号
                detailVO.setAllocateApplyDetailLineNo(index.getSubAllocateApplyOrderLineId());
                //关联单行号
                detailVO.setRelatedAllocateSubOrderId(index.getSubRelatedAllocateSubOrderId());
                //货场仓
                detailVO.setFreightYardId(index.getMainTransferWarehouseId());
                detailVO.setFreightYardReceive(StringUtils.isBlank(index.getMainTransferWarehouseId()) ? Boolean.FALSE : Boolean.TRUE);
                WmsSDO freightYard = wmsMap.get(index.getMainTransferWarehouseId());
                if (freightYard != null){
                    detailVO.setFreightYardCode(freightYard.getCode());
                    detailVO.setFreightYardName(freightYard.getName());
                }
                detailVO.setShipMethod(index.getMainShipMethod() == null ? null : index.getMainShipMethod().toString());
                detailVO.setThirdDetailLineNo(index.getSubThirdLineNo());
                detailVO.setDetailStatus(index.getSubStatus() == null ? null : index.getSubStatus().intValue());
                detailVO.setCloseCode(index.getSubCloseCode());
                detailVO.setDetailFeatures(index.getSubFeatures());
                detailVO.setUnitPrice(index.getSubPrice());
                detailVO.setThirdAllocateOrderId(index.getMainThirdAllocateOrderId());
                detailVO.setMainCreator(index.getMainCreator());
                detailVO.setMainUpdater(index.getMainUpdater());
                //头扩展信息
                detailVO.setHeadFeatures(index.getMainBizFeatures());
                detailVOS.add(detailVO);

            }
        }
        Result<List<AllocateOrderDetailVO>> success = Result.success(detailVOS);
        if (count == null || count.getResult() == null){
            success.setTotal(0);
        }else {
            success.setTotal(count.getResult().intValue());
        }
        log.info("searchES_cost:"+stopWatch.prettyPrint());
        return success;
    }

    @Override
    public Result<List<AllocateOrderDetailVO>> findByAllocateApplyOrderCode(AllocateOrderDetailSearchRequest allocateOrderDetailSearchRequest) {
        List<AllocateOrderDetailVO> vos = Lists.newArrayList();
        if (allocateOrderDetailSearchRequest == null || StringUtils.isBlank(allocateOrderDetailSearchRequest.getAllocateApplyOrderCode())){
            return Result.success(vos);
        }
        allocateOrderDetailSearchRequest.setLimit(500);
        Result<List<OuiAllocateOrderDetailIndex>> search = detailIndexService.search(allocateOrderDetailSearchRequest);
        if (search == null || CollectionUtils.isEmpty(search.getResult())){
            return Result.success(vos);
        }
        for (OuiAllocateOrderDetailIndex index : search.getResult()) {
            AllocateOrderDetailVO vo = new AllocateOrderDetailVO();
            vo.setCode(index.getMainCode());
            vo.setStatus(index.getMainStatus() == null ?null:index.getMainStatus().intValue());
            vo.setStatusStr(InfoUtil.getStatusDesc(index.getMainStatus() == null?null:index.getMainStatus().intValue()));
            vo.setQuantity(index.getSubQuantity());
            vo.setCreateTime(TimeUtil.getDateByLong(index.getMainGmtCreate()));
            vo.setShipTime(TimeUtil.getIgnoreNullDateByLong(index.getSubShipTime()));
            vo.setShipTimeStr(TimeUtil.formatYYYY_MM_dd(vo.getShipTime()));
            vos.add(vo);
        }

        return Result.success(vos);
    }

    /**
     * 纪元调拨单列表
     * @param allocateOrderDetailSearchRequest
     * @return
     */
    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-034",value = "调拨单查询列表")
    public Result<List<AllocateOrderDetailVO>> search(AllocateOrderDetailSearchRequest allocateOrderDetailSearchRequest) {
        log.info("AllocateOrderReadServiceImpl.search.request:{}",JSON.toJSONString(allocateOrderDetailSearchRequest));
        /**
         * 权限数据过滤
         * 先判断当前人角色，调度员、总经理、副总 可以查看 其他角色返回为空
         * 在判断如果是销售组织以上可以查找、销售大区以上所有都回复，其他值返回为空
         * organizationList 组 分公司
         * bizUnitList 单元 销售组织
         */
        boolean isQuery = false;
        String allocateOrderRolesThatCanBeViewed = CrUnifiedInventoryConstants.ALLOCATE_ORDER_ROLES_THATCAN_BE_VIEWED();
        log.info("AllocateOrderReadServiceImpl.searchES.allocateOrderRolesThatCanBeViewed:{}",allocateOrderRolesThatCanBeViewed);
        List<String> list = Lists.newArrayList();
        if (StringUtils.isNotBlank(allocateOrderRolesThatCanBeViewed)){
            list = Arrays.asList(allocateOrderRolesThatCanBeViewed.split(","));
        }
        Map<String,String> map = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(list)){
            for (String s : list) {
                map.put(s,s);
            }
        }
        GetLoginEmployeeInfoResponse getLoginEmployeeInfoResponse = baseDataService.getLoginEmployeeInfo();
        log.info("AllocateOrderReadServiceImpl.searchES.getLoginEmployeeInfo:{}",JSON.toJSONString(getLoginEmployeeInfoResponse));

        if (getLoginEmployeeInfoResponse != null && CollectionUtils.isNotEmpty(getLoginEmployeeInfoResponse.getRoles())){
            //是否是业务员 新增业务员能查看工厂直发的总部销售单权限.
            boolean isSalesMan = false;
            for (RoleSDO role : getLoginEmployeeInfoResponse.getRoles()) {
                String code = map.get(role.getCode());
                if (StringUtils.isNotBlank(code)){
                    isQuery = true;
                }
                //如果是业务员
                if (SALES_MAN_ROLE_CODE.equals(role.getCode())){
                    isSalesMan = true;
                }
            }

            if (getLoginEmployeeInfoResponse != null && getLoginEmployeeInfoResponse.getOrganizationSDO() != null){
                Integer type = getLoginEmployeeInfoResponse.getOrganizationSDO().getType();
                //如果类型是集团 / 事业部 能够查看
                if (Objects.equals(type,100) || Objects.equals(type,101)){
                    isQuery = true;
                }
                /**
                 * GROUP(100, "蒙牛集团"),
                 //                 *     ENTERPRISE_GROUP(101, "事业部"),
                 //                 *     REGION(102, "销售大区"),
                 //                 *     COMPANY(103, "分子公司"),
                 //                 *     SALES_ORGANIZATION(104, "销售组织"),
                 //                 *     SALES_CHANNEL(105, "销售渠道"),
                 //                *     SALES_DEPARTMENT(106, "销售部门");
                 //                 */
                if (Objects.isNull(type) || type > 104){
                    isQuery = false;
                }else {
                    if (type == 103){
                        isQuery = true;
                        allocateOrderDetailSearchRequest.setBizUnitList(getLoginEmployeeInfoResponse.getOrganizationSDO().getId());
                    }
                    if (type == 104){
                        isQuery = true;
                        allocateOrderDetailSearchRequest.setOrganizationList(getLoginEmployeeInfoResponse.getOrganizationSDO().getId());
                    }
                }
                //在这里进行 业务员的特殊判断,2022.02.23
                if (isSalesMan){
                    // 只准看改分子公司下的
                    if (Objects.equals(allocateOrderDetailSearchRequest.getIsDTC(),Boolean.FALSE)){
                        return Result.success(Lists.newArrayList());
                    }
                    allocateOrderDetailSearchRequest.setIsDTC(true);
                    OrganizationSDO organizationSDO = getLoginEmployeeInfoResponse.getOrganizationSDO();
                    //循环找到对应的分子公司层级 type是103 根据父组织id寻找.
                    while (!Objects.equals(103,organizationSDO.getType())){
                        BaselineGetOrganizationById2Request request = new BaselineGetOrganizationById2Request();
                        if (StringUtils.isBlank(organizationSDO.getParentId())){
                            log.info("AllocateOrderReadServiceImpl.searchES.salesMan.org.errorResult:{}",JSON.toJSONString(organizationSDO));
                            break;
                        }
                        request.setId(organizationSDO.getParentId());
                        Result<OrganizationSDO> organizationSDOResult = baseDataService.baselineGetOrganizationById2(request);
                        if (organizationSDOResult == null|| organizationSDOResult.getResult() == null){
                            log.info("AllocateOrderReadServiceImpl.searchES.salesMan.org.errorResult:{}",JSON.toJSONString(organizationSDOResult));
                            break;
                        }
                        organizationSDO = organizationSDOResult.getResult();
                        if (organizationSDO.getType() != null && organizationSDO.getType() < 103){
                            log.info("AllocateOrderReadServiceImpl.searchES.salesMan.org.errorResult:{}",JSON.toJSONString(organizationSDOResult));
                            break;
                        }
                    }
                    //如果是分子公司 就把值给填进去 看该分子公司下的
                    if (Objects.equals(103,organizationSDO.getType())){
                        isQuery = true;
                        allocateOrderDetailSearchRequest.setBizUnitList(organizationSDO.getId());
                    }
                }
            }
        }
        if (isQuery){
            Result<List<AllocateOrderDetailVO>> listResult = searchES(allocateOrderDetailSearchRequest);
            log.info("AllocateOrderReadServiceImpl.search.result:{}",JSON.toJSONString(listResult));
            return listResult;
        }
        log.info("AllocateOrderReadServiceImpl.search.result:{}",Lists.newArrayList());
        return Result.success(Lists.newArrayList());
    }

    /**
     * 状态调拨单列表查询
     */
    @Override
    public Result<List<AllocateOrderDetailVO>> queryTransferOrderSearch(AllocateOrderDetailSearchRequest request) {
        //处理时间参数 获取ES结果
        StopWatch stopWatch = new StopWatch();
        handleSearchConditions(request);

        stopWatch.start("openapi_searchES-get");
        log.info("queryTransferOrderSearch_get_request:{}",JSON.toJSONString(request));
        Result<List<OuiAllocateOrderDetailIndex>> result = detailIndexService.opApiGet(request);
        stopWatch.stop();
        stopWatch.start("openapi_searchES-getCount");
        Result<Long> count = detailIndexService.openApiCount(request);
        stopWatch.stop();
        List<AllocateOrderDetailVO> detailVOS = Lists.newArrayList();
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())){
            Set<String> subAllocateOrderIds = new HashSet<>();
            //预报单id
            Set<String> allocateApplyOrderIds = new HashSet<>();

            //调拨单id
            // Set<String> stoOrderIds = new HashSet<>();
            Set<String> outStoOrderIds = new HashSet<>();
            for (OuiAllocateOrderDetailIndex index : result.getResult()) {
                if (StringUtils.isNotEmpty(index.getMainAllocateApplyOrderId())){
                    allocateApplyOrderIds.add(index.getMainAllocateApplyOrderId());
                }
                // stoOrderIds.add(index.getMainCode());
                outStoOrderIds.add(index.getMainOutAllocateOrderId());
                subAllocateOrderIds.add(String.valueOf(index.getSubAllocateOrderId()));
            }

            //客户、客户地址数据，做成弱依赖
            Map<String,String> orgMap =Maps.newHashMap();
            stopWatch.start("searchES-getOrgMap");
            try {
                orgMap = getOrgMap(result);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getOrgMapInfo error", e);
            }
            stopWatch.stop();
            //仓库
            Map<String,WmsSDO> wmsMap = Maps.newHashMap();
            stopWatch.start("searchES-getWmsMap");
            try {
                wmsMap = composeWmsMap(result);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getWmsMapInfo error", e);
            }
            stopWatch.stop();
            //商品
            Map<String,AllocateOrderDetailBatchGetScItemResponse> scItemResponseMap = Maps.newHashMap();
            stopWatch.start("searchES-getScItemResponseMap");
            try {
                scItemResponseMap = composeScItemResponseMap(result);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getScItemInfo error", e);
            }
            stopWatch.stop();
            //预报单
            stopWatch.start("searchES-queryAllocateApplyOrderMap");
            Map<String,AllocateApplyOrder> allocateApplyOrderMap = queryAllocateApplyOrderMap(new ArrayList<>(allocateApplyOrderIds));
            stopWatch.stop();
            //预报单明细
            stopWatch.start("searchES-queryAllocateApplyOrderDetailMap");
            Map<String,List<AllocateApplyOrderDetail>> stringAllocateApplyOrderDetailMap = queryAllocateApplyOrderDetailMap(Lists.newArrayList(allocateApplyOrderIds));
            stopWatch.stop();
            //交货单
//            stopWatch.start("searchES-getConsignmentOrderMapWithIsECommerceOrder");
//            Map<String,String> consignmentOrderMap = getConsignmentOrderMapWithIsECommerceOrder(result.getResult());
//            stopWatch.stop();
            stopWatch.start("convert_detail");
            for (OuiAllocateOrderDetailIndex index : result.getResult()) {
                AllocateOrderDetailVO detailVO = new AllocateOrderDetailVO();
                BeanUtils.copyProperties(index, detailVO);
                // detailVO.setMainBusinessScenario(index.getMainBusinessScenario());
                detailVO.setType(index.getSubType()==null?null:index.getSubType().intValue());
                detailVO.setTypeDesc(InfoUtil.getTypeDesc(index.getSubType()==null?null:index.getSubType().intValue()));
                detailVO.setCode(index.getMainCode());
                //外部单号，判断牛要客id字段是否有值，如果有值用牛要客字段的值，如果没有取外部单号的值
                detailVO.setOutAllocateOrderId(StringUtils.isNotBlank(index.getMainNykId())?index.getMainNykId():index.getMainOutAllocateOrderId());
                detailVO.setAllocateApplyOrderCode(index.getMainAllocateApplyOrderCode());
                detailVO.setLineNo(index.getSubLineNo() == null?null:index.getSubLineNo().toString());
                detailVO.setOutAllocateOrderLineId(index.getSubOutAllocateOrderLineId());
                detailVO.setAllocateApplyOrderLineId(index.getSubAllocateApplyOrderLineId());
                detailVO.setApplyOrgId(index.getMainApplyOrgId());
                //是否电商调拨单
                boolean isECommerceOrder = InfoUtil.isECommerceOrder(index.getMainReceiveOrgId());
                detailVO.setApplyOrgName(orgMap.get(index.getMainApplyOrgId()));
                detailVO.setProductGroup("11");
                detailVO.setProductGroupDesc("常温");
                detailVO.setStatus(index.getMainStatus()==null?null:index.getMainStatus().intValue());
                detailVO.setStatusDesc(InfoUtil.getStatusEpochDesc(index.getMainStatus()==null?null:index.getMainStatus().intValue()));
                detailVO.setStatusStr(InfoUtil.getStatusDesc(index.getMainStatus()==null?null:index.getMainStatus().intValue()));
                detailVO.setIsDTC(Objects.equals(index.getMainIsDTC(), 1L));
                detailVO.setIsDTCDesc(Objects.equals(index.getMainIsDTC(),1L)?"是":"否");
                detailVO.setReturnOrder(InfoUtil.getBoolean(index.getMainReturnOrder()));
                detailVO.setReturnOrderDesc(InfoUtil.getBooleanDesc(index.getMainReturnOrder()));
                // 仓库 收发组织
                detailVO.setReceiveAreaId(index.getMainReceiveAreaId());
                WmsSDO receiveWmsSDO = wmsMap.get(index.getMainReceiveAreaId());
                if (receiveWmsSDO != null){
                    detailVO.setReceiveAreaName(receiveWmsSDO.getName());
                    detailVO.setReceiveFactoryCode(receiveWmsSDO.getFactoryCode());
                    detailVO.setReceiveInventoryCode(receiveWmsSDO.getInventoryCode());
                    detailVO.setReceiveAreaCode(receiveWmsSDO.getCode());
                }
                WmsSDO receiveWarehouseWmsSDO =  wmsMap.get(index.getMainReceiveWarehouseId());
                if (receiveWarehouseWmsSDO != null){
                    detailVO.setReceiveWarehouseName(receiveWarehouseWmsSDO.getName());
                    //收货物理仓编码
                    detailVO.setReceiveWarehouseCode(receiveWarehouseWmsSDO.getCode());
                }
                detailVO.setReceiveOrgId(index.getMainReceiveOrgId());
                detailVO.setReceiveOrgName(orgMap.get(index.getMainReceiveOrgId()));
                detailVO.setShipAreaId(index.getMainShipAreaId());
                detailVO.setShipOrgId(index.getMainShipOrgId());
                detailVO.setShipOrgName(orgMap.get(index.getMainShipOrgId()));
                WmsSDO shipWmsSDO = wmsMap.get(index.getMainShipAreaId());
                if (shipWmsSDO != null){
                    detailVO.setShipAreaName(shipWmsSDO.getName());
                    detailVO.setShipFactoryCode(shipWmsSDO.getFactoryCode());
                    detailVO.setShipInventoryCode(shipWmsSDO.getInventoryCode());
                    detailVO.setShipAreaCode(shipWmsSDO.getCode());
                }
                WmsSDO shipWarehouseWmsSDO = wmsMap.get(index.getMainShipWarehouseId());
                if (shipWarehouseWmsSDO != null){
                    detailVO.setShipWarehouseName(shipWarehouseWmsSDO.getName());
                    detailVO.setShipWarehouseCode(shipWarehouseWmsSDO.getCode());
                }
                // 客户编码
                detailVO.setCustomer(index.getMainCustomer());
                //如果状态是关闭的, 且发货数量 > 0(已关闭,部分发货) 或收货数量 > 0(已关闭,部分收货), 理论上全部发货关闭不了
                if (AllocateOrderStatus.CLOSED.getValue().equals(index.getSubStatus()==null?null:index.getSubStatus().intValue())){
                    if (index.getSubReceiveQuantity() != null && index.getSubReceiveQuantity() > 0){
                        detailVO.setLineStatusDesc(InfoUtil.getStatusEpochDesc(AllocateOrderStatus.CLOSED_AND_PARTRECEIVED.getValue()));
                    }else if (index.getSubShipQuantity() != null && index.getSubShipQuantity() > 0){
                        detailVO.setLineStatusDesc(InfoUtil.getStatusEpochDesc(AllocateOrderStatus.CLOSED_AND_PARTSHIPPED.getValue()));
                    }else {
                        detailVO.setLineStatusDesc(InfoUtil.getStatusEpochDesc(AllocateOrderStatus.CLOSED.getValue()));
                    }
                }else {
                    detailVO.setLineStatusDesc(InfoUtil.getStatusEpochDesc(index.getSubStatus()==null?
                            null:index.getSubStatus().intValue()));
                }

                //如果状态是关闭的, 且发货数量 > 0(已关闭,部分发货) 或收货数量 > 0(已关闭,部分收货), 理论上全部发货关闭不了
                if (AllocateOrderStatus.CLOSED.getValue().equals(index.getSubStatus()==null?null:index.getSubStatus().intValue())){
                    if (index.getSubReceiveQuantity() != null && index.getSubReceiveQuantity() > 0){
                        detailVO.setLineStatusStr(InfoUtil.getStatusDesc(AllocateOrderStatus.CLOSED_AND_PARTRECEIVED.getValue()));
                    }else if (index.getSubShipQuantity() != null && index.getSubShipQuantity() > 0){
                        detailVO.setLineStatusStr(InfoUtil.getStatusDesc(AllocateOrderStatus.CLOSED_AND_PARTSHIPPED.getValue()));
                    }else {
                        detailVO.setLineStatusStr(InfoUtil.getStatusDesc(AllocateOrderStatus.CLOSED.getValue()));
                    }
                }else {
                    detailVO.setLineStatusStr(InfoUtil.getStatusDesc(index.getSubStatus()==null?null:index.getSubStatus().intValue()));
                }
//                detailVO.setStatus(index.getMainStatus()==null?null:index.getMainStatus().intValue());
//                detailVO.setStatusDesc(InfoUtil.getStatusEpochDesc(detailVO.getStatus()));

                detailVO.setScItemId(index.getSubScItemId());
                detailVO.setScItemCode(index.getSubScItemCode());
                AllocateOrderDetailBatchGetScItemResponse scItemResponse = scItemResponseMap.get(index.getSubScItemId());
                if (scItemResponse != null){
                    detailVO.setScItemName(scItemResponse.getTitle());
                    if (StringUtils.isBlank(detailVO.getScItemCode())){
                        detailVO.setScItemCode(scItemResponse.getScItemCode());
                    }
                }
                detailVO.setShipMethodDesc(InfoUtil.getShipMethodDesc(index.getMainShipMethod() == null?null:
                        index.getMainShipMethod().intValue()));
                detailVO.setQuantity(InfoUtil.handleQuantityDate(index.getSubQuantity()));
                if (Objects.equals(Boolean.TRUE,InfoUtil.getBoolean(index.getMainReturnOrder()))){
                    detailVO.setConfirmQuantity(InfoUtil.handleQuantityDate(index.getSubQuantity()));
                }else {
                    detailVO.setConfirmQuantity(InfoUtil.handleQuantityDate(index.getSubConfirmQuantity()));
                }
                //  交货数量 取值交货单更新
                detailVO.setDeliveryQuantity(index.getSubDeliveryQuantity());
                detailVO.setShipQuantity(index.getSubShipQuantity()==null?null:index.getSubShipQuantity().toString());
                //es没有收货数量
                detailVO.setReceiveQuantity(index.getSubReceiveQuantity()==null?null:index.getSubReceiveQuantity().toString());
                detailVO.setNotIssuedQuantity(InfoUtil.handleQuantityDate(InfoUtil.subtract(index.getSubQuantity(),index.getSubShipQuantity())));
                //退单在途数量=0；
                if (Objects.equals(Boolean.TRUE,InfoUtil.getBoolean(index.getMainReturnOrder()))){
                    detailVO.setTransQuantity("0");
                }else {
                    detailVO.setTransQuantity(InfoUtil.subtract(index.getSubShipQuantity(),index.getSubReceiveQuantity()));
                }
                //es没有赠送数量
//                detailVO.setGiftQuantity(index.getSubGiftQuantity());
                detailVO.setUnit(index.getSubUnit());
                detailVO.setPrice(index.getSubPrice());
//                detailVO.setDiscountPrice(InfoUtil.getDiscountPrice(index.getSubSubTotalAmount(),index.getSubQuantity()));
                detailVO.setAmount(InfoUtil.multiply(index.getSubPrice(),index.getSubQuantity()));
                //结算金额
//                detailVO.setCrossCompanySettlement(index.getSubExchangeAmt());
                //这个地方得保证 折后金额和小计金额的一致性.
//                detailVO.setDiscountAmt(index.getSubDiscountAmount());
                //TODO 交货金额哪里来.
//                detailVO.setDeliveryAmt(InfoUtil.multiply(index.getSubPrice(),index.getSubDeliveryQuantity()));
//                detailVO.setDeliveryDiscountAmt(InfoUtil.multiply(detailVO.getDiscountPrice(),index.getSubDeliveryQuantity()));
//                detailVO.setShippedDiscountAmt(InfoUtil.multiply(index.getSubShipQuantity() ==null?null:index.getSubShipQuantity().toString(),detailVO.getDiscountPrice()));;
//                detailVO.setShippedAmt(InfoUtil.multiply(index.getSubShipQuantity()==null?null:index.getSubShipQuantity().toString(),index.getSubPrice()));
//                detailVO.setTaxRate(index.getSubTaxRate());
                detailVO.setExpectedProductDate(TimeUtil.getDateByLong(index.getSubExpectedProduceDate()));
                detailVO.setExpectedProductDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getExpectedProductDate()));
                detailVO.setExpectedDeliveryDate(TimeUtil.getDateByLong(index.getMainExpectedDeliveryDate()));
                detailVO.setExpectedDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getExpectedDeliveryDate()));
                detailVO.setLineExpectedDeliveryDate(TimeUtil.getDateByLong(index.getSubExpectedDeliveryDate()));
                detailVO.setLineExpectedDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getLineExpectedDeliveryDate()));
//                detailVO.setSendBackRequired(InfoUtil.getBoolean(index.getMainSendBackRequired()));
//                detailVO.setSendBackRequiredDesc(InfoUtil.getBooleanDesc(index.getMainSendBackRequired()));
                detailVO.setCloseReason(index.getSubCloseReason());
                detailVO.setCloseDesc(InfoUtil.getBooleanDesc(index.getSubClose()));
                detailVO.setClosed(InfoUtil.getBoolean(index.getSubClose()));
                detailVO.setLineRemark(index.getSubRemarks());
                // TODO 这个和期待生产日期的区别  暂时没有
                detailVO.setProductDate(TimeUtil.getDateByLong(index.getSubExpectedProduceDate()));
                detailVO.setProductDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getProductDate()));
                //TODO 出库生产日期是  出入库单的生产日期 多值 逗号
                detailVO.setOutWarehouseProductDate(null);
                //时间直接使用gmt了.
//                detailVO.setCreateTime(index.getMainCreateTime()==null?InfoUtil.getDate(index.getMainGmtCreate()):InfoUtil.getDate(index.getMainCreateTime()));
                detailVO.setCreateTime(InfoUtil.getDate(index.getMainGmtCreate()));
                detailVO.setSubCreateTime(InfoUtil.getDate(index.getSubGmtCreate()));
                //确认日期是 确认数量变化的时间 sap找sap 回复创建调拨单时间
                detailVO.setConfirmDate(TimeUtil.getIgnoreNullDateByLong(index.getSubConfirmTime()));
                detailVO.setConfirmDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getConfirmDate()));
                // 交货日期
                if (index.getSubDeliveryDate()!= null && index.getSubDeliveryDate() == new Date(0).getTime()){
                    detailVO.setDeliveryDate(null);
                }else {
                    detailVO.setDeliveryDate(TimeUtil.getDateByLong(index.getSubDeliveryDate()));
                }
                detailVO.setDeliveryDate(TimeUtil.getDateByLong(index.getSubDeliveryDate()));
                detailVO.setDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getDeliveryDate()));
                //TODO 出库日期 ? 发货时间
//                detailVO.setShipTime(TimeUtil.getIgnoreNullDateByLong(index.getSubShipTime()));
//                detailVO.setShipTimeStr(TimeUtil.formatYYYY_MM_dd(detailVO.getShipTime()));
//                detailVO.setOutWarehouseDate(null);
//                detailVO.setReceiveDate(null);
//                detailVO.setReceiveTime(TimeUtil.getIgnoreNullDateByLong(index.getSubReceiveTime()));
//                detailVO.setReceiveTimeStr(TimeUtil.formatYYYY_MM_dd(detailVO.getReceiveTime()));
                if (receiveWarehouseWmsSDO != null){
                    detailVO.setReceiveAreaContactor(receiveWarehouseWmsSDO.getContactPerson());
                    detailVO.setReceiveAreaPhone(receiveWarehouseWmsSDO.getPhone());
                    detailVO.setReceiveAreaAddress(receiveWarehouseWmsSDO.getAddress());
                }
                //TODO 单据日期的写入 需要再看
                detailVO.setDocDate(InfoUtil.getDate(index.getMainDocDate()));
                detailVO.setDocDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getDocDate()));
                //TODO 生效日期
                detailVO.setBeginDate(null);
                detailVO.setLineExpectedDeliveryDate(InfoUtil.getDate(index.getSubExpectedDeliveryDate()));
                detailVO.setLineExpectedDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getLineExpectedDeliveryDate()));
//                detailVO.setCreator(NameUtil.getRealName(index.getMainCreator()));

                //detailVO.setCreator(InfoUtil.getRealName(index.getMainCreator()));
//                detailVO.setCreator(InfoUtil.getRealName(index.getSubCreator()));
                detailVO.setCreateTime(InfoUtil.getDate(index.getMainGmtCreate()));
                //detailVO.setCreateTime(InfoUtil.getDate(index.getSubGmtCreate()));
                //TODO 提交时间
                detailVO.setSubmitTime(InfoUtil.getDate(index.getMainSubmitTime()));
//                detailVO.setUpdator(NameUtil.getRealName(index.getMainUpdater()));
//                detailVO.setUpdator(InfoUtil.getRealName(index.getMainUpdater()));
                detailVO.setUpdateTime(InfoUtil.getDate(index.getMainGmtModified()));
                detailVO.setRemark(index.getMainRemark());
                detailVO.setOrderReasonDesc(EnumUtils.getOrderReason(index.getMainOrderReason()));
                //判断仓库是否有值
                if(Objects.nonNull(receiveWmsSDO)) {
                    detailVO.setSapInternalSalesBPCode(receiveWmsSDO.getSapInternalSalesBPCode());
                    detailVO.setSapInternalDeliveryBPCode(receiveWmsSDO.getSapInternalDeliveryBPCode());
                    detailVO.setSapSalesBPCode(receiveWmsSDO.getSapSalesBPCode());
                    detailVO.setSapDeliveryBPCode(receiveWmsSDO.getSapDeliveryBPCode());
                }
                detailVO.setSapCostCenter(index.getMainSapCostCenter());
                detailVO.setSapRefPoNo(index.getMainSapRefPoNo());
                detailVO.setSapSalesOrgId(index.getMainSapSalesOrgId());
                detailVO.setSapChannel(index.getMainSapChannel());
                detailVO.setUnit(InfoUtil.convertUnit(index.getSubUnit()));
                detailVO.setMessage(index.getMainMessage());

                //外部调拨预报单号
                AllocateApplyOrder allocateApplyOrder = allocateApplyOrderMap.get(index.getMainAllocateApplyOrderId());
                if (Objects.nonNull(allocateApplyOrder)){
                    detailVO.setOutAllocateApplyOrderId(allocateApplyOrder.getOutAllocateApplyOrderId());
                }
                List<AllocateApplyOrderDetail> allocateApplyOrderDetails = stringAllocateApplyOrderDetailMap.get(index.getMainAllocateApplyOrderId());
                if (CollectionUtils.isNotEmpty(allocateApplyOrderDetails)){
                    long sum = allocateApplyOrderDetails.stream().filter(x -> Objects.equals(x.getGoodsId(), index.getSubScItemId()) && x.getApplyQuantity() != null).mapToLong(AllocateApplyOrderDetail::getApplyQuantity).sum();
                    detailVO.setApplyQuantity(String.valueOf(sum));
                }

                //确认未发货数量 确认未发量】=确认数量 confirmQuantity-收货数量 receiveQuantity-在途数量 transQuantity
                if (StringUtils.isNotEmpty(detailVO.getConfirmQuantity())){
                    int receiveQuantity = 0;
                    int transQuantity = 0;
                    if (StringUtils.isNotEmpty(detailVO.getReceiveQuantity())){
                        receiveQuantity = Integer.parseInt(detailVO.getReceiveQuantity());
                    }
                    if (StringUtils.isNotEmpty(detailVO.getTransQuantity())){
                        transQuantity = Integer.parseInt(detailVO.getTransQuantity());
                    }
                    int confirmQuantity  = Integer.parseInt(detailVO.getConfirmQuantity())-receiveQuantity-transQuantity;
                    detailVO.setConfirmUndeliveredQuantity(confirmQuantity +"");
                }
                //未确认数量 未确认数量=订单数量 quantity -确认数量 confirmQuantity
                if (StringUtils.isNotEmpty(detailVO.getQuantity())){
                    int confirmQuantity = 0;
                    if (StringUtils.isNotEmpty(detailVO.getConfirmQuantity())){
                        confirmQuantity = Integer.parseInt(detailVO.getConfirmQuantity());
                    }
                    int unconfirmedQuantity  = Integer.parseInt(detailVO.getQuantity())-confirmQuantity;
                    detailVO.setUnconfirmedQuantity(Integer.toString(unconfirmedQuantity));
                }
//                detailVO.setAddressCode(index.getMainAddressCode());
//                if (receiveWarehouseWmsSDO != null &&
//                        StringUtils.isNotBlank(receiveWarehouseWmsSDO.getAddress()) &&
//                        Objects.equals(index.getMainType()==null?null:index.getMainType().intValue(),
//                                AllocateOrderTypeEnum.HEADQUARTER_SALES.getType().intValue())){
//                    detailVO.setSapCustomerAddressName(receiveWarehouseWmsSDO.getAddress());
//                }
                //2023.5.21系统来源和业态
                detailVO.setFromSys(index.getMainFromSys());
                detailVO.setBusinessType(index.getMainBusinessType());
//                //sap信贷校验
//                detailVO.setCreditCheck(index.getMainCreditCheck());
//                //sap信贷校验状态
//                detailVO.setCreditCheckStatus(index.getMainCreditCheckStatus());

                //关联单号
                detailVO.setRelatedAllocateOrderCode(index.getMainRelatedAllocateOrderCode());
                //履约方式
                detailVO.setFulfillmentTypeCode(index.getMainFulfillmentTypeCode());
                //履约优先级
                detailVO.setPriority(index.getMainPriority());
                //订单标签
                detailVO.setOrderTag(index.getMainOrderTag());
                //自动履约
                detailVO.setAutoFulfillment(index.getMainAutoFulfillment());
                detailVO.setThirdDetailLineNo(index.getSubThirdLineNo());
                detailVO.setOutDetailLineNo(index.getSubOutAllocateOrderLineId());
                //预报单行号
                detailVO.setAllocateApplyDetailLineNo(index.getSubAllocateApplyOrderLineId());
                //关联单行号
                detailVO.setRelatedAllocateSubOrderId(index.getSubRelatedAllocateSubOrderId());
                //货场仓
                detailVO.setFreightYardId(index.getMainTransferWarehouseId());
                detailVO.setFreightYardReceive(StringUtils.isBlank(index.getMainTransferWarehouseId()) ? Boolean.FALSE : Boolean.TRUE);
                WmsSDO freightYard = wmsMap.get(index.getMainTransferWarehouseId());
                if (freightYard != null){
                    detailVO.setFreightYardCode(freightYard.getCode());
                    detailVO.setFreightYardName(freightYard.getName());
                }
                detailVO.setShipMethod(index.getMainShipMethod() == null ? null : index.getMainShipMethod().toString());
                detailVO.setThirdDetailLineNo(index.getSubThirdLineNo());
                detailVO.setDetailStatus(index.getSubStatus() == null ? null : index.getSubStatus().intValue());
                detailVO.setCloseCode(index.getSubCloseCode());
                detailVO.setDetailFeatures(index.getSubBizFeatures());
                detailVO.setUnitPrice(index.getSubPrice());
                detailVO.setThirdAllocateOrderId(index.getMainThirdAllocateOrderId());

//                String creator = index.getMainCreator();
//                if (StringUtils.isNotBlank(creator)) {
//                    String realName = InfoUtil.getRealName(index.getMainUpdater());
//                    if (StringUtils.isNotBlank(realName) && !"系统".equals(realName)) {
//                        creator = realName;
//                    }
//                }
//                detailVO.setMainCreator(creator);
//                String updater = index.getMainUpdater();
//                if (StringUtils.isNotBlank(updater)) {
//                    String realName = InfoUtil.getRealName(index.getMainUpdater());
//                    if (StringUtils.isNotBlank(realName) && !"系统".equals(realName)) {
//                        updater = realName;
//                    }
//                }
//                detailVO.setMainUpdater(updater);
                detailVO.setMainCreator(index.getMainCreatorName());
                detailVO.setMainUpdater(index.getMainModifierName());
                //头扩展信息
                detailVO.setHeadFeatures(index.getMainBizFeatures());
                //小计金额
                detailVO.setSubTotalAmount(index.getSubSubTotalAmount());
                detailVOS.add(detailVO);

            }
            stopWatch.stop();
        }
        Result<List<AllocateOrderDetailVO>> success = Result.success(detailVOS);
        if (count == null || count.getResult() == null){
            success.setTotal(0);
        }else {
            success.setTotal(count.getResult().intValue());
        }
        log.info("openapi_searchES_cost:"+stopWatch.prettyPrint());
        return success;
    }

    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-022")
    public Result<AllocateOrderDetailsQueryResponse> query(
            AllocateOrderDetailsQueryRequest allocateOrderDetailsQueryRequest) {
        StopWatch stopWatch = new StopWatch();
        log.info("AllocateOrderReadServiceImpl.query.request:{}",JSON.toJSONString(allocateOrderDetailsQueryRequest));
        stopWatch.start("query-queryDetail");
        AllocateOrderDetailsQueryResponse r = allocateOrderReadRepository.queryDetail(allocateOrderDetailsQueryRequest);
        stopWatch.stop();
        if (StringUtils.isBlank(allocateOrderDetailsQueryRequest.getCode()) || r.getId() == null){
            log.info("AllocateOrderReadServiceImpl.query.result:{}",JSON.toJSONString(r));
            return Result.success(r);
        }

        if (!Boolean.FALSE.equals(allocateOrderDetailsQueryRequest.getSearchEs())) {
            AllocateOrderDetailSearchRequest searchRequest = new AllocateOrderDetailSearchRequest();
            searchRequest.setCode(allocateOrderDetailsQueryRequest.getCode());
            searchRequest.setLimit(1000);
            stopWatch.start("query-searchESl");
            Result<List<AllocateOrderDetailVO>> listResult = searchES(searchRequest);
            stopWatch.stop();
            if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                //把明细的创建时间赋值到创建时间上
                listResult.getResult().forEach(allocateOrderDetailVO -> {
                    if (allocateOrderDetailVO.getSubCreateTime() != null){
                        allocateOrderDetailVO.setCreateTime(allocateOrderDetailVO.getSubCreateTime());
                    }
                });
                r.setAllocateOrderDetailVOList(listResult.getResult());
//            List<AllocateOrderScItemDetailDTO> allocateOrderScItemDetailDTOS = Lists.newArrayList();
//
//            //计算金额
//            BigDecimal orderAmount = new BigDecimal(0);
//            for (AllocateOrderDetailVO detailVO : listResult.getResult()) {
//                AllocateOrderScItemDetailDTO dto = new AllocateOrderScItemDetailDTO();
//                dto.setApplyQuantity(detailVO.getQuantity());
//                dto.setExpectedDeliveryDate(detailVO.getLineExpectedDeliveryDate());
//                dto.setGoodsId(detailVO.getScItemId());
//                dto.setId(detailVO.getScItemId());
//                dto.setScItemId(detailVO.getScItemCode());
//                dto.setLineNo(detailVO.getLineNo());
//                dto.setTitle(detailVO.getScItemName());
//                dto.setUnitPrice(detailVO.getPrice());
//                dto.setRemark(detailVO.getLineRemark());
//                dto.setProductDate(TimeUtil.formatYYYY_MM_dd(detailVO.getExpectedProductDate()));
//                //货品金额
//                BigDecimal goodsAmount = new BigDecimal(0);
//                //数量
//                String quantity = detailVO.getQuantity();
//                //单价
//                String price = detailVO.getPrice();
//                if (StringUtils.isNotEmpty(quantity)&&StringUtils.isNotEmpty(price)){
//                    goodsAmount = new BigDecimal(quantity).multiply(new BigDecimal(price));
//                }
//                detailVO.setGoodsAmount(goodsAmount);
//                orderAmount = orderAmount.add(goodsAmount);
//                allocateOrderScItemDetailDTOS.add(dto);
//            }
//            r.setOrderAmount(orderAmount);
//            r.setAllocateOrderScItemDetailDTOS(allocateOrderScItemDetailDTOS);
            }
        }

        //编辑草稿时 从库里查询
        AllocateOrderDetailLoadListRequest allocateOrderDetailLoadListRequest = new AllocateOrderDetailLoadListRequest();
        allocateOrderDetailLoadListRequest.setLimit(MAX_PAGE_SIZE);
        allocateOrderDetailLoadListRequest.setAllocateOrderId(r.getId());
        stopWatch.start("query-loadAllocateOrderDetailList");
        Result<List<AllocateOrderDetail>> detailList = allocateOrderDetailService.loadAllocateOrderDetailList(allocateOrderDetailLoadListRequest);
        stopWatch.stop();
        if (detailList != null && CollectionUtils.isNotEmpty(detailList.getResult())){
            List<String> scItemIds = detailList.getResult().stream().map(AllocateOrderDetail::getScItemId).filter(x -> StringUtils.isNotBlank(x))
                    .distinct().collect(Collectors.toList());
            Map<String, AllocateOrderDetailBatchGetScItemResponse> scItemMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(scItemIds)){
                scItemMap = InfoUtil.getScItemMap(scItemIds);
            }
            List<AllocateOrderScItemDetailDTO> allocateOrderScItemDetailDTOS = Lists.newArrayList();
            //计算金额
            BigDecimal orderAmount = new BigDecimal(0);
            for (AllocateOrderDetail detail : detailList.getResult()) {
                AllocateOrderScItemDetailDTO dto = new AllocateOrderScItemDetailDTO();
                dto.setApplyQuantity(detail.getQuantity());
                dto.setExpectedDeliveryDate(detail.getExpectedDeliveryDate());
                dto.setGoodsId(detail.getScItemId());
                dto.setId(detail.getScItemId());
                dto.setScItemId(detail.getScItemCode());
                dto.setScItemCode(detail.getScItemCode());
                dto.setLineNo(detail.getLineNo()==null?null:detail.getLineNo().toString());
                AllocateOrderDetailBatchGetScItemResponse scItemResponse = scItemMap.get(detail.getScItemId());
                if (scItemResponse != null){
                    dto.setTitle(scItemResponse.getTitle());
                }
                dto.setUnitPrice(detail.getPrice());
                dto.setRemark(detail.getRemarks());
                dto.setProductDate(TimeUtil.formatYYYY_MM_dd(detail.getExpectedProduceDate()));
                dto.setUnit(detail.getUnit());
                //货品金额
                BigDecimal goodsAmount = new BigDecimal(0);
                //数量
                String quantity = detail.getQuantity();
                //单价
                String price = detail.getPrice();
                if (StringUtils.isNotEmpty(quantity)&&StringUtils.isNotEmpty(price)){
                    goodsAmount = new BigDecimal(quantity).multiply(new BigDecimal(price));
                }
                List<AllocateOrderDetailVO> detailVOList = r.getAllocateOrderDetailVOList();
                if (CollectionUtils.isNotEmpty(detailVOList)){
                    AllocateOrderDetailVO detailVO = detailVOList.stream().filter(x -> Objects.equals(x.getScItemId(), detail.getScItemId())).findFirst().orElse(null);
                    if (detailVO != null){
                        detailVO.setGoodsAmount(goodsAmount);
                    }
                }
//                detailVO.setGoodsAmount(goodsAmount);
                orderAmount = orderAmount.add(goodsAmount);
                if (StringUtils.isNotBlank(detail.getThirdLineNo())) {
                    dto.setThirdLineNo(detail.getThirdLineNo());
                } else {
                    dto.setThirdLineNo(detail.getOutAllocateOrderLineId());
                }
                dto.setQuantity(detail.getQuantity());
                dto.setRelatedAllocateSubOrderId(detail.getRelatedAllocateSubOrderId());
                dto.setAllocateApplyOrderLineId(detail.getAllocateApplyOrderLineId());
                dto.setAllocateApplyOrderLineNo(detail.getAllocateApplyOrderLineId());
                allocateOrderScItemDetailDTOS.add(dto);
            }
            r.setOrderAmount(orderAmount);
            r.setAllocateOrderScItemDetailDTOS(allocateOrderScItemDetailDTOS);
        }


        //获取入库单
        AllocateOrderGetInOutOrderRequest inOutOrderRequest = new AllocateOrderGetInOutOrderRequest();

        try{
            if (r != null && r.getId() != null){
                AllocateOrderGetInOutOrderRequest allocateOrderGetInOutOrderRequest = new AllocateOrderGetInOutOrderRequest();
                allocateOrderGetInOutOrderRequest.setAllocateOrderId(r.getId().toString());
                allocateOrderGetInOutOrderRequest.setStatusList(Lists.newArrayList(WmsStatusEnum.Normal.getValue()));
                allocateOrderGetInOutOrderRequest.setSize(800);
                log.info("AllocateOrderReadServiceImpl.query.getListOutinForAllocation.request:{}",JSON.toJSONString(allocateOrderGetInOutOrderRequest));
                //这个是出入明细
                stopWatch.start("query-getListOutinForAllocation");
                GetListOutinForAllocationResponse inOutResponse = unifiedInventoryService.getListOutinForAllocation(allocateOrderGetInOutOrderRequest);
                stopWatch.stop();
                log.info("AllocateOrderReadServiceImpl.query.getListOutinForAllocation.request:{}",JSON.toJSONString(inOutResponse));
                List<InWarehouseDetailDTO> inDetailDTOs = getInWarehouseDetailDTOS(inOutResponse);
                List<OutWarehouseDetailDTO> outDetailDTOs = getOutWarehouseDetailDTOS(inOutResponse);
                //获取到货品的map
                Map<String, AllocateOrderDetailBatchGetScItemResponse> scItemMap = Maps.newHashMap();
                List<String> scItemIds = Lists.newArrayList();
                //获取到出入库明细的id
                if (CollectionUtils.isNotEmpty(inDetailDTOs)){
                    List<String> collect = inDetailDTOs.stream().map(InWarehouseDetailDTO::getScItemId).filter(StringUtils::isNotBlank)
                            .distinct()
                            .collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(collect)){
                        scItemIds.addAll(collect);
                    }
                }
                if (CollectionUtils.isNotEmpty(outDetailDTOs)){
                    List<String> collect = outDetailDTOs.stream().map(OutWarehouseDetailDTO::getScItemId).filter(StringUtils::isNotBlank)
                            .distinct().collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(collect)){
                        scItemIds.addAll(collect);
                    }
                }
                //货品id再去重一下
                if (CollectionUtils.isNotEmpty(scItemIds)){
                    scItemIds = scItemIds.stream().distinct().collect(Collectors.toList());
                    scItemMap = InfoUtil.getScItemMap(scItemIds);
                }
                if (CollectionUtils.isNotEmpty(inDetailDTOs)){
                    for (InWarehouseDetailDTO dto : inDetailDTOs) {
                        if (StringUtils.isNotBlank(dto.getProductionDate())){
                            String[] s = dto.getProductionDate().split(" ");
                            if (s != null && s.length > 0){
                                dto.setProductionDate(s[0]);
                            }
                        }
                        //赋值货品编码
                        AllocateOrderDetailBatchGetScItemResponse scItemResponse = scItemMap.get(dto.getScItemId());
                        if (scItemResponse != null && StringUtils.isNotBlank(scItemResponse.getScItemCode())){
                            dto.setScItemCode(scItemResponse.getScItemCode());
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(outDetailDTOs)){
                    for (OutWarehouseDetailDTO dto : outDetailDTOs) {
                        if (StringUtils.isNotBlank(dto.getProductionDate())){
                            String[] s = dto.getProductionDate().split(" ");
                            if(s != null && s.length > 0){
                                dto.setProductionDate(s[0]);
                            }
                        }
                        //赋值货品编码
                        AllocateOrderDetailBatchGetScItemResponse scItemResponse = scItemMap.get(dto.getScItemId());
                        if (scItemResponse != null && StringUtils.isNotBlank(scItemResponse.getScItemCode())){
                            dto.setScItemCode(scItemResponse.getScItemCode());
                        }
                    }
                }

                r.setOutWarehouseDetailDTOS(outDetailDTOs);
                r.setInWarehouseDetailDTOS(inDetailDTOs);

                //出入库单
                AllocateOrderGetWmsOrdersRequest allocateOrderGetWmsOrdersRequest = new AllocateOrderGetWmsOrdersRequest();
                allocateOrderGetWmsOrdersRequest.setAllocateOrderId(r.getId().toString());
                allocateOrderGetWmsOrdersRequest.setStatus(WmsStatusEnum.Normal.getValue());
                allocateOrderGetWmsOrdersRequest.setSize(800);
                log.info("AllocateOrderReadServiceImpl.query.getWmsOrders.request:{}",JSON.toJSONString(allocateOrderGetWmsOrdersRequest));
                stopWatch.start("query-getWmsOrders");
                Object wmsOrders = unifiedInventoryService.getWmsOrders(allocateOrderGetWmsOrdersRequest);
                stopWatch.stop();
                log.info("AllocateOrderReadServiceImpl.query.getWmsOrders.result:{}",JSON.toJSONString(wmsOrders));
                List<InAndOutOfWarehouseOrderDTO> inAndOutOfWarehouseOrderDTOS = getInAndOutOfWarehouseOrderDTOS(wmsOrders);
                r.setInAndOutOfWarehouseOrderDTOS(inAndOutOfWarehouseOrderDTOS);

            }
        }catch (Exception e){
            log.error("AllocateOrderReadServiceImpl.query:",e);
        }
        log.info("AllocateOrderReadServiceImpl.query.result:{}",JSON.toJSONString(r));
        log.info("query stopWatch "+stopWatch.prettyPrint());
        return Result.success(r);
    }

    /**
     * 通过 出入库明细获取调拨单id
     * @param response
     * @return
     */
    public static String getAllocateOrderId(GetListOutinForAllocationResponse response){
        if (response != null && CollectionUtils.isNotEmpty(response.getResult())) {
            for (Object obj : response.getResult()) {
                if (obj == null) {
                    continue;
                }
                JSONObject js = JSONObject.parseObject(JSON.toJSONString(obj));
                if (js == null) {
                    continue;
                }
                String sourceSubOrderId = js.getString("sourceSubOrderId");
                if (StringUtils.isNotBlank(sourceSubOrderId)) {
                    return sourceSubOrderId;
                }
            }
        }
        return null;
    }

    public static List<OutWarehouseDetailDTO> getOutWarehouseDetailDTOS(GetListOutinForAllocationResponse response){
        List<OutWarehouseDetailDTO> detailDTOS = Lists.newArrayList();
        if (response != null && CollectionUtils.isNotEmpty(response.getResult())){
            for (Object obj : response.getResult()) {
                if (obj == null)continue;
                JSONObject js = JSONObject.parseObject(JSON.toJSONString(obj));
                if (js==null)continue;
                String type = js.getString("mainOrderType");
                if ("2".equals(type) || "2.0".equals(type)){
                    OutWarehouseDetailDTO dto = new OutWarehouseDetailDTO();
                    dto.setOutCode(js.getString("outSubOrderId"));
                    dto.setCode(js.getString("wmsSubOrderId"));
                    dto.setCreateTime(js.getString("gmtCreate"));
                    dto.setOutSubOrderId(js.getString("outSubOrderId"));
//                dto.setStatusDesc(js.getString("mainOrderTypeDesc"));
                    dto.setScItemName(js.getString("goodsName"));
                    dto.setBatch(js.getString("batchNo"));
                    dto.setProductionDate(js.getString("dom"));
//                    dto.setQuantity(js.getString("goodsQuantity"));
                    dto.setQuantity(js.getString("goodsQuantityFormat"));
                    dto.setScItemCode(js.getString("goodsId"));
                    dto.setScItemId(js.getString("goodsId"));
                    dto.setStatus(js.getString("status"));
                    dto.setSourceSubOrderId(js.getString("sourceSubOrderId"));
                    detailDTOS.add(dto);
                }
            }
        }
        return detailDTOS;
    }

    public static List<InWarehouseDetailDTO> getInWarehouseDetailDTOS(GetListOutinForAllocationResponse response){
        List<InWarehouseDetailDTO> detailDTOS = Lists.newArrayList();
        if (response != null && CollectionUtils.isNotEmpty(response.getResult())){
            for (Object obj : response.getResult()) {
                if (obj == null)continue;
                JSONObject js = JSONObject.parseObject(JSON.toJSONString(obj));
                if (js==null)continue;
                String type = js.getString("mainOrderType");
                if ("1".equals(type) || "1.0".equals(type)){
                    InWarehouseDetailDTO dto = new InWarehouseDetailDTO();
                    dto.setOutCode(js.getString("outSubOrderId"));
                    dto.setCode(js.getString("wmsSubOrderId"));
                    dto.setCreateTime(js.getString("gmtCreate"));
                    dto.setOutSubOrderId(js.getString("outSubOrderId"));
//                dto.setStatusDesc(js.getString("mainOrderTypeDesc"));
                    dto.setScItemName(js.getString("goodsName"));
                    dto.setBatch(js.getString("batchNo"));
                    dto.setProductionDate(js.getString("dom"));
//                    dto.setQuantity(js.getString("goodsQuantity"));
                    dto.setQuantity(js.getString("goodsQuantityFormat"));
                    dto.setScItemCode(js.getString("goodsId"));
                    dto.setScItemId(js.getString("goodsId"));
                    //库存判断
                    dto.setStatus(js.getString("status"));
                    detailDTOS.add(dto);
                }
            }
        }
        return detailDTOS;
    }


    //转换
    public static List<WmsMainOrder> convertWmsMainOrderList(Object wmsOrder){
        List<WmsMainOrder> wmsMainOrders = Lists.newArrayList();
        if (wmsOrder == null){
            return wmsMainOrders;
        }
        JSONObject result = JSON.parseObject(JSON.toJSONString(wmsOrder));
        if (result == null){
            return wmsMainOrders;
        }
        result = result.getJSONObject("result");
        if (result == null){
            return wmsMainOrders;
        }
        JSONArray array = result.getJSONArray("warehousingOrders");
        if (array != null && array.size() > 0) {
            for (int i = 0; i < array.size(); i++) {
                JSONObject obj = array.getJSONObject(i);
                if (obj == null) {
                    continue;
                }
                String shipPhone = obj.getString("shipPhone");
                String shipNo = obj.getString("shipNo");
                String orderStatus = obj.getString("orderStatus");
                String postingTime = obj.getString("postingTime");
                String outWarehousingOrderId = obj.getString("outWarehousingOrderId");
                String outAllocateOrderId = obj.getString("outAllocateOrderId");
                WmsMainOrder wmsMainOrder = new WmsMainOrder();
                wmsMainOrder.setShipPhone(shipPhone);
                wmsMainOrder.setShipNo(shipNo);
                wmsMainOrder.setOrderStatus(orderStatus);
                wmsMainOrder.setPostingTime(postingTime);
                wmsMainOrder.setOutWarehousingOrderId(outWarehousingOrderId);
                wmsMainOrder.setOutAllocateOrderId(outAllocateOrderId);
                wmsMainOrders.add(wmsMainOrder);
            }
        }
        return wmsMainOrders;
    }

    public static String getAllocateOrderIdByWmsOrder(Object wmsOrder){
        if (wmsOrder == null){
            return null;
        }
        JSONObject result = JSON.parseObject(JSON.toJSONString(wmsOrder));
        if (result == null){
            return null;
        }
        result = result.getJSONObject("result");
        if (result == null){
            return null;
        }
        JSONArray array = result.getJSONArray("warehousingOrders");
        if (array != null && array.size() > 0) {
            for (int i = 0; i < array.size(); i++) {
                JSONObject obj = array.getJSONObject(i);
                if (obj == null) {
                    continue;
                }
                String sourceWarehousingOrderId = obj.getString("sourceWarehousingOrderId");
                if (StringUtils.isNotBlank(sourceWarehousingOrderId)){
                    return sourceWarehousingOrderId;
                }
            }
        }
        return null;
    }

    //获取出入
    public static  List<InAndOutOfWarehouseOrderDTO> getInAndOutOfWarehouseOrderDTOS(Object wmsOrder){
        if (wmsOrder == null){
            return null;
        }
        JSONObject result = JSON.parseObject(JSON.toJSONString(wmsOrder));
        if (result == null){
            return null;
        }
        result = result.getJSONObject("result");
        if (result == null){
            return null;
        }
        JSONArray array = result.getJSONArray("warehousingOrders");
        List<InAndOutOfWarehouseOrderDTO> list = Lists.newArrayList();
        if (array != null && array.size() > 0){
            for (int i =0;i<array.size();i++){
                JSONObject obj = array.getJSONObject(i);
                if (obj == null)continue;
                InAndOutOfWarehouseOrderDTO dto = new InAndOutOfWarehouseOrderDTO();
                String orderStatus = obj.getString("orderStatus");
                if ("2.0".equals(orderStatus) || "2".equals(orderStatus)){
                    dto.setStatusDesc("完成");
                }else if ("-1.0".equals(orderStatus) || "1.0".equals(orderStatus)){
                    dto.setStatusDesc("取消");
                }
//                dto.setTotalQuantity(obj.getString("sumQuantity"));
                dto.setTotalQuantity(obj.getString("sumQuantityFormat"));
                dto.setCode(obj.getString("warehousingOrderId"));
                dto.setOutCode(obj.getString("sourceWarehousingOrderId"));
                //外部出入库单号
                dto.setOutWarehousingOrderId(obj.getString("outWarehousingOrderId"));
//                dto.setCreateTime(TimeUtil.parseTime(obj.getString("createTime")));
                //createTime -> 2022-01-20 21:59:46
                dto.setCreateTime(TimeUtil.parseTime(obj.getString("createTime")));
                dto.setCompleteTime(TimeUtil.parseSimpleDateFormat(obj.getString("postingTime")));
                dto.setCarInfo(obj.getString("shipNo"));
                dto.setPhone(obj.getString("shipPhone"));
                dto.setDriver(obj.getString("shipContact"));
                dto.setSourceWarehousingOrderId(obj.getString("sourceWarehousingOrderId"));
                dto.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(obj.getString("expectedDate")));
                dto.setExpectedDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(dto.getExpectedDeliveryDate()));
                list.add(dto);
            }
        }
        return list;

    }


    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-079", value = "获取出入库单明细出错")
    public Result<AllocateOrderGetWmsSDOResponse> getWmsSDO(AllocateOrderGetWmsSDORequest allocateOrderGetWmsSDORequest) {
        log.info("AllocateOrderReadServiceImpl.getWmsSDO.request:{}",JSON.toJSONString(allocateOrderGetWmsSDORequest));
        AllocateOrderGetWmsSDOResponse response = new AllocateOrderGetWmsSDOResponse();
        if (allocateOrderGetWmsSDORequest  == null || StringUtils.isBlank(allocateOrderGetWmsSDORequest.getId())){
            return Result.success(response);
        }

        WmsSDO wmsSDO = InfoUtil.getWmsSDO(allocateOrderGetWmsSDORequest.getId());
        if (wmsSDO != null){
            response.setId(wmsSDO.getId());
            response.setSapDeliveryBPCode(wmsSDO.getSapDeliveryBPCode());
            response.setSapSalesBPCode(wmsSDO.getSapSalesBPCode());
            response.setName(wmsSDO.getName());
            response.setSapInternalDeliveryBPCode(wmsSDO.getSapInternalDeliveryBPCode());
            response.setSapInternalSalesBPCode(wmsSDO.getSapInternalSalesBPCode());
        }

        log.info("AllocateOrderReadServiceImpl.getWmsSDO.response:{}",JSON.toJSONString(response));
        return Result.success(response);
    }

    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-035",value = "获取调拨单消息")
    public Result<AllocateOrderMessageResponse> getAllocateOrderMessage(AllocateOrderGetMessageRequest allocateOrderGetMessageRequest) {
        log.info("AllocateOrderReadServiceImpl.getAllocateOrderMessage.request:{}",JSON.toJSONString(allocateOrderGetMessageRequest));
        if (allocateOrderGetMessageRequest == null || StringUtils.isAllBlank(allocateOrderGetMessageRequest.getCode(),
                allocateOrderGetMessageRequest.getId())){
//            throw new FacadeException("OTS-03-005-00-15-010");
            return Result.fail("OTS-03-005-00-15-010", "调拨单id和code参数不能同时为空");
        }
        AllocateOrderRequest request = new AllocateOrderRequest();
        if (StringUtils.isNotBlank(allocateOrderGetMessageRequest.getId())){
            request.setAllocateOrderId(allocateOrderGetMessageRequest.getId());
        }
        if (StringUtils.isNotBlank(allocateOrderGetMessageRequest.getCode())){
            request.setAllocateOrderCode(allocateOrderGetMessageRequest.getCode());
        }
        AllocateOrderWithOrderDetailsSDO sdo = allocateOrderReadRepository.get(request);
        if (sdo == null || sdo.getAllocateOrderSDO() == null){
//            throw new FacadeException("OTS-03-005-00-15-004");
            return Result.fail("OTS-03-005-00-15-004", "调拨单查询不存在");
        }
        if (CollectionUtils.isEmpty(sdo.getAllocateOrderDetailSDOS())){
//            throw new FacadeException("OTS-03-005-00-15-003");
            return Result.fail("OTS-03-005-00-15-003", "调拨单提交的货品明细不能为空");
        }
        AllocateOrderMessageResponse response = new AllocateOrderMessageResponse();
        AllocateOrderSDO allocateOrderSDO = sdo.getAllocateOrderSDO();
        List<AllocateOrderDetailSDO> detailSDOS = sdo.getAllocateOrderDetailSDOS();
        response.setId(allocateOrderSDO.getId()==null?null:allocateOrderSDO.getId().toString());
        response.setCode(allocateOrderSDO.getCode());
        response.setReceiveAreaId(allocateOrderSDO.getReceiveAreaId());
        response.setShipAreaId(allocateOrderSDO.getShipAreaId());
        response.setShipWarehouseId(allocateOrderSDO.getShipWarehouseId());
        response.setReceiveWarehouseId(allocateOrderSDO.getReceiveWarehouseId());
        List<AllocateOrderDetailMessageDTO> list = Lists.newArrayList();
        for (AllocateOrderDetailSDO detailSDO : detailSDOS){
            AllocateOrderDetailMessageDTO dto = new AllocateOrderDetailMessageDTO();
            dto.setId(detailSDO.getId() == null?null: detailSDO.getId().toString());
            dto.setPrice(detailSDO.getPrice());
            dto.setProductDate(detailSDO.getExpectedProduceDate());
//            dto.setScItemCode(InfoUtil.deleteZeroPrefix(detailSDO.getScItemCode()));
            dto.setScItemCode(InfoUtil.subStringScItmCode(detailSDO.getScItemCode()));
            dto.setUnit(detailSDO.getUnit());
            dto.setQuantity(detailSDO.getQuantity() == null? null:InfoUtil.getInt(detailSDO.getQuantity().trim()));
            String scItemName = InfoUtil.getScItemName(detailSDO.getScItemId());
            dto.setScItemName(scItemName);
            dto.setScItemId(detailSDO.getScItemId());
            list.add(dto);
        }
        response.setAllocateOrderDetailMessageDTOList(list);
        log.info("AllocateOrderReadServiceImpl.getAllocateOrderMessage.result:{}",JSON.toJSONString(response));

        return Result.success(response);
    }

    public static String divide(String val1, String val2){
        if (StringUtils.isAnyBlank(val1,val2))return null;
        return new BigDecimal(val1).divide(new BigDecimal(val2))
                .setScale(2, RoundingMode.HALF_UP).toString();
    }

    public static String getPrice(Long price){
        if (price == null)return null;
        BigDecimal v = new BigDecimal(price);
        return v.movePointLeft(2).toString();
    }

    /**
     * 获取未发数量
     * @param confirmQuantity
     * @param shipQuantity
     * @return
     */
    public static String getNotIssuedQuantity(String confirmQuantity,String shipQuantity){
        if (StringUtils.isBlank(confirmQuantity))return null;
        if (StringUtils.isBlank(shipQuantity))return confirmQuantity;

        BigDecimal confirm  = new BigDecimal(confirmQuantity);
        BigDecimal ship = new BigDecimal(confirmQuantity);
        return confirm.subtract(ship).toString();
    }

    public static String subtract(String val1,String val2){
        if (StringUtils.isBlank(val1))return null;
        if (StringUtils.isBlank(val2))return val1;
        BigDecimal var1B = new BigDecimal(val1);
        BigDecimal var2B = new BigDecimal(val2);
        return var1B.subtract(var2B).toString();
    }

    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-023",value = "通过调拨预报单号查询调拨单")
    public Result<AllocateOrderQueryResponse> queryByAllocateApplyOrderCode(AllocateApplyOrderCodeQueryRequest request) {
        log.info("AllocateOrderReadServiceImpl.queryByAllocateApplyOrderCode.request:{}",JSON.toJSONString(request));
        String allocateApplyOrderCode = request.getAllocateApplyOrderCode();
        List<AllocateOrderSDO> allocateOrderSDOS =
                allocateOrderReadRepository.queryByAllocateApplyOrderCode(allocateApplyOrderCode);
        if (CollectionUtils.isEmpty(allocateOrderSDOS)){
            return Result.success(null);
        }
        List<AllocateOrderDTO> list = Lists.newArrayList();
        for (AllocateOrderSDO sdo : allocateOrderSDOS){
            AllocateOrderDetailsQueryRequest r = new AllocateOrderDetailsQueryRequest();
            r.setAllocateOrderId(String.valueOf(sdo.getId()));
            List<AllocateOrderDetailSDO> detailSDOS = allocateOrderDetailReadRepository.query(r);
            AllocateOrderDTO allocateOrderDTO = JsonUtil.convert(sdo,AllocateOrderDTO.class);
            List<AllocateOrderScItemDetail> allocateOrderScItemDetails = JsonUtil.convertList(detailSDOS,AllocateOrderScItemDetail.class);

            allocateOrderDTO.setAllocateOrderScItemDetails(allocateOrderScItemDetails);
            list.add(allocateOrderDTO);
        }
        AllocateOrderQueryResponse response = new AllocateOrderQueryResponse();
        response.setAllocateOrderDTOS(list);
        log.info("AllocateOrderReadServiceImpl.queryByAllocateApplyOrderCode.result:{}",JSON.toJSONString(response));
        return Result.success(response);
    }

    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-024")
    @Deprecated//弃用了
    public Result<AllocateOrderSubmitSAPResponse> createSubmitSAPRequest(AllocateOrderSubmitSAPRequest request) {
        AllocateOrderSubmitSAPResponse response = new AllocateOrderSubmitSAPResponse();
        return Result.success(response);
    }

    @Override
    public Result<AllocateOrderGetCustomerResponse> getCustomer(AllocateOrderGetCustomerRequest allocateOrderGetCustomerRequest) {
        AllocateOrderGetCustomerResponse customerResponse =
                allocateOrderReadRepository.getCustomer(allocateOrderGetCustomerRequest);
        return Result.success(customerResponse);
    }

    /**
     * 查询客户信息
     * @param
     * @return
     */
//    @Override
//    public Result<AllocateOrderGetCustomerResponse> getCustomer(AllocateOrderGetCustomerRequest request) {
//        AllocateOrderGetCustomerResponse customerResponse = allocateOrderReadRepository.getCustomer(request);
//        return Result.success(customerResponse);
//    }

    @Override
    public Result<AllocateOrderBatchGetWarehouseResponse> getWarehouse(AllocateOrderGetWarehouseRequest allocateOrderGetWarehouseRequest) {
        return AllocateOrderReadService.super.getWarehouse(allocateOrderGetWarehouseRequest);
    }

    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-025",value = "获取在途单据")
    public Result<List<AloocateOrderGetTransResponse>> getTransOrder(AloocateOrderGetTransRequest aloocateOrderGetTransRequest) {
        log.info("AllocateOrderReadServiceImpl.getTransOrder.request:{}",JSON.toJSONString(aloocateOrderGetTransRequest));
//        List<AloocateOrderGetTransResponse> responses = allocateOrderReadRepository.getTransOrder(aloocateOrderGetTransRequest);
        Result<List<AloocateOrderGetTransResponse>> responses = allocateOrderReadRepository.getTransOrder(aloocateOrderGetTransRequest);
//        Result result  = Result.success(responses);
//        result.setTotal(CollectionUtils.isEmpty(responses)?0:responses.size());
        log.info("AllocateOrderReadServiceImpl.getTransOrder.result:{}",JSON.toJSONString(responses));
        return  responses;
    }

    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-026",value = "获取退单信息")
    public Result<AllocateOrderReturnOrderInfoResponse> getReturnOrderInfo(AllocateOrderReturnOrderRequest allocateOrderReturnOrderRequest) {
        log.info("AllocateOrderReadServiceImpl.getReturnOrderInfo.request:{}",JSON.toJSONString(allocateOrderReturnOrderRequest));
        AllocateOrderReturnOrderInfoResponse response = allocateOrderReadRepository.getReturnOrderInfo(allocateOrderReturnOrderRequest);
        log.info("AllocateOrderReadServiceImpl.getReturnOrderInfo.result:{}",JSON.toJSONString(response));
        return Result.success(response);
    }

    /**
     *  根据预报单号list 查询调拨单明细
     * @param allocateOrderDetailSearchRequest
     * @return
     */
    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-027",value = "查询为调拨预报单")
    public Result<List<AllocateOrderDetailVO>> searchForAllocateApplyOrder(AllocateOrderDetailSearchRequest allocateOrderDetailSearchRequest) {
        allocateOrderDetailSearchRequest.setLimit(800);
        allocateOrderDetailSearchRequest.setDir("subId");
        allocateOrderDetailSearchRequest.setAsc(false);
        if (allocateOrderDetailSearchRequest == null ||
                CollectionUtils.isEmpty(allocateOrderDetailSearchRequest.getAllocateApplyOrderCodeList())){
            return Result.success(Lists.newArrayList());
        }
        log.info("AllocateOrderReadServiceImpl.searchForAllocateApplyOrder.request:{}",JSON.toJSONString(allocateOrderDetailSearchRequest));

        Result<List<OuiAllocateOrderDetailIndex>> result = detailIndexService.search(allocateOrderDetailSearchRequest);
        log.info("AllocateOrderReadServiceImpl.searchForAllocateApplyOrder.es.result:{}",JSON.toJSONString(result));

        List<AllocateOrderDetailVO> detailVOS = Lists.newArrayList();
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())){
            Set<String> subAllocateOrderIds = new HashSet<>();

            //调拨单id
            for (OuiAllocateOrderDetailIndex index : result.getResult()) {
                subAllocateOrderIds.add(String.valueOf(index.getSubAllocateOrderId()));
            }

            //出入库单明细
            Map<String,List<OutWarehouseDetailDTO>> inOutResponseMap = Maps.newHashMap();
            //出入库明细response
            Map<String,GetListOutinForAllocationResponse> allocationMap = Maps.newHashMap();
            try {
//                inOutResponseMap = getInOutResponseMap(subAllocateOrderIds);
                evalInOutResponseMaps(subAllocateOrderIds,inOutResponseMap,allocationMap);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getInOutInfo error", e);
            }
            //出库单
//            Map<String,List<InAndOutOfWarehouseOrderDTO>> wmsOrdersMap = Maps.newHashMap();
            //存放出入库单用于后期查询
            Map<String,Object> wmsOrdersMap = Maps.newHashMap();
            try {
                wmsOrdersMap = getWmsOrders(subAllocateOrderIds);
            } catch (Throwable e) {
                log.error("AllocateOrderReadServiceImpl.enrichInfo.getWmsOrderInfo error", e);
            }

            for (OuiAllocateOrderDetailIndex index : result.getResult()){
                AllocateOrderDetailVO detailVO = new AllocateOrderDetailVO();
                detailVO.setId(index.getSubId());
                detailVO.setAllocateOrderId(index.getMainId()==null?null:index.getMainId().toString());
                detailVO.setAllocateApplyOrderCode(index.getMainAllocateApplyOrderCode());
                detailVO.setAllocateApplyOrderId(index.getMainAllocateApplyOrderId());
                detailVO.setCode(index.getMainCode());
                detailVO.setType(index.getMainType() == null?null:index.getMainType().intValue());
                detailVO.setShipQuantity(index.getSubShipQuantity()==null?null:index.getSubShipQuantity().toString());
                detailVO.setReceiveQuantity(index.getSubReceiveQuantity() == null? null: index.getSubReceiveQuantity().toString());
                detailVO.setDeliveryQuantity(index.getSubDeliveryQuantity() == null?null:index.getSubDeliveryQuantity().toString());
                detailVO.setScItemId(index.getSubScItemId());
                detailVO.setScItemCode(index.getSubScItemCode());
                detailVO.setClosed(index.getSubStatus() != null && (7L == index.getSubStatus()));

                //这个是出入明细
//                AllocateOrderGetInOutOrderRequest allocateOrderGetInOutOrderRequest = new AllocateOrderGetInOutOrderRequest();
//                allocateOrderGetInOutOrderRequest.setAllocateOrderId(index.getSubAllocateOrderId());
//                allocateOrderGetInOutOrderRequest.setStatusList(Lists.newArrayList(WmsStatusEnum.Normal.getValue()));
//                allocateOrderGetInOutOrderRequest.setSize(800);
//                log.info("AllocateOrderReadServiceImpl.searchForAllocateApplyOrder.getListOutinForAllocation.request:{}",JSON.toJSONString(allocateOrderGetInOutOrderRequest));
//                GetListOutinForAllocationResponse inOutResponse = unifiedInventoryService.getListOutinForAllocation(allocateOrderGetInOutOrderRequest);
//                log.info("AllocateOrderReadServiceImpl.searchForAllocateApplyOrder.getListOutinForAllocation.result:{}",JSON.toJSONString(inOutResponse));

//                List<InWarehouseDetailDTO> inDetailDTOs = getInWarehouseDetailDTOS(inOutResponse);
                List<OutWarehouseDetailDTO> outDetailDTOs = inOutResponseMap.get(index.getSubAllocateOrderId());
                if (CollectionUtils.isNotEmpty(outDetailDTOs)){
                    List<OutWarehouseDetailDTO> out = outDetailDTOs.stream().filter(Objects::nonNull)
                            .filter(x -> Objects.equals(x.getScItemId(), index.getSubScItemId()))
                            .collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(out)){
                        List<String> outProductDates = out.stream().filter(x->StringUtils.isNotBlank(x.getProductionDate()))
                                .map(OutWarehouseDetailDTO::getProductionDate)
                                .map(TimeUtil::getYYYYMMddFromTimeFormat).filter(Objects::nonNull)
                                .distinct().collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(outProductDates)){
                            detailVO.setOutWarehouseProductDateDesc(StringUtils.join(outProductDates,","));
                        }
//                       detailVO.setOutWarehouseDateDesc(out.get(0).getOutWarehouseTime());
                        detailVO.setOutWarehouseDate(out.get(0).getOutWarehouseTime());
                    }
                }

                //出入库单的 物流信息
                //出入库单
//                AllocateOrderGetWmsOrdersRequest allocateOrderGetWmsOrdersRequest = new AllocateOrderGetWmsOrdersRequest();
//                allocateOrderGetWmsOrdersRequest.setAllocateOrderId(index.getSubAllocateOrderId());
//                allocateOrderGetWmsOrdersRequest.setStatus(WmsStatusEnum.Normal.getValue());
//                allocateOrderGetWmsOrdersRequest.setSize(300);
//                log.info("AllocateOrderReadServiceImpl.searchForAllocateApplyOrder.getWmsOrders.request:{}",JSON.toJSONString(allocateOrderGetWmsOrdersRequest));
//                Object wmsOrders = unifiedInventoryService.getWmsOrders(allocateOrderGetWmsOrdersRequest);
//                log.info("AllocateOrderReadServiceImpl.searchForAllocateApplyOrder.getWmsOrders.result:{}",JSON.toJSONString(wmsOrders));

                Object wms = wmsOrdersMap.get(index.getSubAllocateOrderId());
                GetListOutinForAllocationResponse forAllocationResponse = allocationMap.get(index.getSubAllocateOrderId());

//                List<InAndOutOfWarehouseOrderDTO> inAndOutOfWarehouseOrderDTOS = getInAndOutOfWarehouseOrderDTOS(wmsOrders);
//                if (CollectionUtils.isNotEmpty(inAndOutOfWarehouseOrderDTOS)){
                if (wms != null){

                    if (!StringUtils.isAnyBlank(detailVO.getCode(),detailVO.getScItemId())){
//                        List<AllocateOrderLogisticsInfoResponse> logisticsInfo = getLogisticsInfo(detailVO.getCode(), detailVO.getScItemId());

                        List<AllocateOrderLogisticsInfoResponse> logisticsInfo = getLogisticsInfo(forAllocationResponse,wms, detailVO.getScItemId());
//                        List<AllocateOrderLogisticsInfoResponse> logisticsInfo = getLogisticsInfo(detailVO.getCode(), detailVO.getScItemId());
                        log.info("AllocateOrderReadServiceImpl.searchForAllocateApplyOrder.getLogisticsInfo.result:{}",JSON.toJSONString(logisticsInfo));
                        if (CollectionUtils.isNotEmpty(logisticsInfo)){
                            List<String> collect = logisticsInfo.stream().filter(Objects::nonNull)
                                    .filter(x-> StringUtils.isNotBlank(x.getCarNo()))
                                    .map(AllocateOrderLogisticsInfoResponse::getCarNo)
                                    .distinct()
                                    .collect(Collectors.toList());
                            if (CollectionUtils.isNotEmpty(collect)){
                                detailVO.setLogisticsInfo(StringUtils.join(collect,","));
                            }
                        }

                    }
                }

                if (Objects.equals(Boolean.TRUE,InfoUtil.getBoolean(index.getMainReturnOrder()))){
                    detailVO.setConfirmQuantity(InfoUtil.handleQuantityDate(index.getSubQuantity()));
                }else {
                    detailVO.setConfirmQuantity(InfoUtil.handleQuantityDate(index.getSubConfirmQuantity()));
                }
                detailVOS.add(detailVO);

            }
        }
        log.info("AllocateOrderReadServiceImpl.searchForAllocateApplyOrder.result:{}",JSON.toJSONString(detailVOS));

        return Result.success(detailVOS);
    }

    /**
     * 物流信息展示
     * @param allocateOrderGetLogisticsInfoRequest
     * @return
     */
    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-028",value = "物流信息展示")
    public Result<List<AllocateOrderLogisticsInfoResponse>> getLogisticsInfo(AllocateOrderGetLogisticsInfoRequest allocateOrderGetLogisticsInfoRequest) {
        log.info("AllocateOrderReadServiceImpl.getLogisticsInfo.request:{}",JSON.toJSONString(allocateOrderGetLogisticsInfoRequest));

        if (StringUtils.isBlank(allocateOrderGetLogisticsInfoRequest.getScItemId())
                || StringUtils.isAllBlank(allocateOrderGetLogisticsInfoRequest.getAllocateApplyOrderCode(),
                allocateOrderGetLogisticsInfoRequest.getCode())){
            log.info("AllocateOrderReadServiceImpl.getLogisticsInfo.result:{}",JSON.toJSONString(Lists.newArrayList()));
            return Result.success(Lists.newArrayList());
        }
        List<AllocateOrderLogisticsInfoResponse> responses = Lists.newArrayList();
        if (StringUtils.isNotBlank(allocateOrderGetLogisticsInfoRequest.getAllocateApplyOrderCode())){
            AllocateOrderLoadListRequest loadListRequest = new AllocateOrderLoadListRequest();
            loadListRequest.setAllocateApplyOrderCode(allocateOrderGetLogisticsInfoRequest.getAllocateApplyOrderCode());
            loadListRequest.setLimit(800);
            Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(loadListRequest);
            if (listResult != null &&  CollectionUtils.isNotEmpty(listResult.getResult())){
                for (AllocateOrder allocateOrder : listResult.getResult()) {
                    List<AllocateOrderLogisticsInfoResponse> logisticsInfo = getLogisticsInfo(allocateOrder.getCode(), allocateOrderGetLogisticsInfoRequest.getScItemId());
                    if (CollectionUtils.isNotEmpty(logisticsInfo)){
                        //现在不要求显示出入库单号了
                        for (AllocateOrderLogisticsInfoResponse logisticsInfoResponse : logisticsInfo) {
                            if (logisticsInfoResponse != null && CollectionUtils.isNotEmpty(logisticsInfoResponse.getAllocateOrderLogisticsInfoList())){
                                for (AllocateOrderLogisticsInfoDTO allocateOrderLogisticsInfoDTO : logisticsInfoResponse.getAllocateOrderLogisticsInfoList()) {
                                    allocateOrderLogisticsInfoDTO.setTitle(null);
                                }
                            }
                        }
                        responses.addAll(logisticsInfo);
                    }
                }
            }
        }else if (StringUtils.isNotBlank(allocateOrderGetLogisticsInfoRequest.getCode())){
            responses = getLogisticsInfo(allocateOrderGetLogisticsInfoRequest.getCode(),
                    allocateOrderGetLogisticsInfoRequest.getScItemId());
            if (responses != null && CollectionUtils.isNotEmpty(responses)){
                Collections.reverse(responses);
            }
        }
        log.info("AllocateOrderReadServiceImpl.getLogisticsInfo.result:{}",JSON.toJSONString(responses));

        return Result.success(responses);
//        AllocateOrderGetWmsOrdersRequest request = new AllocateOrderGetWmsOrdersRequest();
//        List<AllocateOrderLogisticsInfoResponse> logisticsInfo = getLogisticsInfo("STO22021112200000003", "297590774238455152");
//        return AllocateOrderReadService.super.getLogisticsInfo(allocateOrderGetLogisticsInfoRequest);
    }


    /** 获取物流信息 **/
    public List<AllocateOrderLogisticsInfoResponse> getLogisticsInfo(GetListOutinForAllocationResponse listOutInForAllocation,
                                                                     Object wmsOrders,
                                                                     String scItemId){
//        AllocateOrderLoadListRequest request = new AllocateOrderLoadListRequest();
//        request.setCode(code);
//        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(request);
//        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())){
//            return Lists.newArrayList();
//        }
//        AllocateOrder allocateOrder = listResult.getResult().get(0);
//        if (allocateOrder == null || allocateOrder.getId() ==null){
//            return Lists.newArrayList();
//        }
//        AllocateOrderGetWmsOrdersRequest wmsOrdersRequest = new AllocateOrderGetWmsOrdersRequest();
//        wmsOrdersRequest.setAllocateOrderId(allocateOrder.getId().toString());
//        wmsOrdersRequest.setStatus(WmsStatusEnum.Normal.getValue());
//        wmsOrdersRequest.setSize(800);
//        Object wmsOrders = unifiedInventoryService.getWmsOrders(wmsOrdersRequest);
//        AllocateOrderGetInOutOrderRequest getInOutOrderRequest = new AllocateOrderGetInOutOrderRequest();
//        log.info("AllocateOrderReadServiceImpl.getLogisticsInfo.getLogisticsInfo.getWmsOrders.result:{}",JSON.toJSONString(wmsOrders));
//
//        getInOutOrderRequest.setAllocateOrderId(allocateOrder.getId().toString());
//        getInOutOrderRequest.setStatusList(Lists.newArrayList(WmsStatusEnum.Normal.getValue()));
//        getInOutOrderRequest.setSize(800);
//        GetListOutinForAllocationResponse listOutInForAllocation = unifiedInventoryService.getListOutinForAllocation(getInOutOrderRequest);
//        log.info("AllocateOrderReadServiceImpl.getLogisticsInfo.getLogisticsInfo.getListOutinForAllocation.result:{}",JSON.toJSONString(listOutInForAllocation));

        List<AllocateOrderLogisticsInfoResponse> responses = getAllocateOrderLogisticsInfoResponses(listOutInForAllocation, wmsOrders, scItemId);
        return  responses;
    }

    public List<AllocateOrderLogisticsInfoResponse> getLogisticsInfo(String code,String scItemId){
        AllocateOrderLoadListRequest request = new AllocateOrderLoadListRequest();
        request.setCode(code);
        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(request);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())){
            return Lists.newArrayList();
        }
        AllocateOrder allocateOrder = listResult.getResult().get(0);
        if (allocateOrder == null || allocateOrder.getId() ==null){
            return Lists.newArrayList();
        }
        AllocateOrderGetWmsOrdersRequest wmsOrdersRequest = new AllocateOrderGetWmsOrdersRequest();
        wmsOrdersRequest.setAllocateOrderId(allocateOrder.getId().toString());
        wmsOrdersRequest.setStatus(WmsStatusEnum.Normal.getValue());
        wmsOrdersRequest.setSize(800);
        Object wmsOrders = unifiedInventoryService.getWmsOrders(wmsOrdersRequest);
        AllocateOrderGetInOutOrderRequest getInOutOrderRequest = new AllocateOrderGetInOutOrderRequest();
        log.info("AllocateOrderReadServiceImpl.getLogisticsInfo.getLogisticsInfo.getWmsOrders.result:{}",JSON.toJSONString(wmsOrders));

        getInOutOrderRequest.setAllocateOrderId(allocateOrder.getId().toString());
        getInOutOrderRequest.setStatusList(Lists.newArrayList(WmsStatusEnum.Normal.getValue()));
        getInOutOrderRequest.setSize(800);
        GetListOutinForAllocationResponse listOutInForAllocation = unifiedInventoryService.getListOutinForAllocation(getInOutOrderRequest);
        log.info("AllocateOrderReadServiceImpl.getLogisticsInfo.getLogisticsInfo.getListOutinForAllocation.result:{}",JSON.toJSONString(listOutInForAllocation));

        List<AllocateOrderLogisticsInfoResponse> responses = getAllocateOrderLogisticsInfoResponses(listOutInForAllocation, wmsOrders, scItemId);
        return  responses;
    }

    /**
     * 找出调拨单明细 和 scItemId 出入库单 和出入库详情 根据车牌 分组 主单和详情 根据 外部单号关联
     * 得出 车牌 -> 出入库单号
     */
    public static List<AllocateOrderLogisticsInfoResponse>
    getAllocateOrderLogisticsInfoResponses(GetListOutinForAllocationResponse response,
                                           Object wmsOrder,
                                           String scItemId){
        List<AllocateOrderLogisticsInfoResponse> list = Lists.newArrayList();
        if (wmsOrder == null){
            return list;
        }
        JSONObject orderResult = JSONObject.parseObject(JSON.toJSONString(wmsOrder));
        if (orderResult == null){
            return list;
        }
        JSONObject detailResult = JSONObject.parseObject(JSON.toJSONString(response));
        if (detailResult == null){
            return list;
        }

        List<InAndOutOfWarehouseOrderDTO> warehouseOrderDTOS = getInAndOutOfWarehouseOrderDTOS(wmsOrder);
        if (CollectionUtils.isEmpty(warehouseOrderDTOS)){
            return list;
        }
        //获取出库
        List<OutWarehouseDetailDTO> outWarehouseDetailDTOS = getOutWarehouseDetailDTOS(response);
        //获取入库
        List<InWarehouseDetailDTO> inWarehouseDetailDTOS = getInWarehouseDetailDTOS(response);
        if (CollectionUtils.isEmpty(inWarehouseDetailDTOS) && CollectionUtils.isEmpty(outWarehouseDetailDTOS)){
            return list;
        }
        //去掉车牌空的
        warehouseOrderDTOS =
                warehouseOrderDTOS.stream().filter(Objects::nonNull)
                        .filter(x->StringUtils.isNotBlank(x.getCarInfo())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(warehouseOrderDTOS)){
            return list;
        }
        //出库明细  匹配货品
        outWarehouseDetailDTOS = outWarehouseDetailDTOS.stream().filter(x->StringUtils.isNotBlank(scItemId)
                && scItemId.equals(x.getScItemId())).collect(Collectors.toList());
        //入库明细 匹配货品
        inWarehouseDetailDTOS = inWarehouseDetailDTOS.stream()
                .filter(x->StringUtils.isNotBlank(scItemId) && scItemId.equals(x.getScItemId())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(outWarehouseDetailDTOS) && CollectionUtils.isEmpty(inWarehouseDetailDTOS)){
            return list;
        }
        Map<String,List<InWarehouseDetailDTO>> inMap = Maps.newHashMap();
        Map<String,List<OutWarehouseDetailDTO>> outMap = Maps.newHashMap();
        //循环出入库单
        for (InAndOutOfWarehouseOrderDTO dto : warehouseOrderDTOS) {
            if (StringUtils.isNotBlank(dto.getOutWarehousingOrderId())){
                //找到匹配的入库明细
                List<InWarehouseDetailDTO> in = inWarehouseDetailDTOS.stream().
                        filter(x->dto.getOutWarehousingOrderId().equals(x.getOutSubOrderId()))
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(in)){
                    List<InWarehouseDetailDTO> ins = inMap.get(dto.getCarInfo());
                    if (CollectionUtils.isEmpty(ins)){
                        inMap.put(dto.getCarInfo(),in);
                    }else {
                        ins.addAll(in);
                        inMap.put(dto.getCarInfo(),ins);
                    }

                }
                //找到匹配的出库明细
                List<OutWarehouseDetailDTO> out = outWarehouseDetailDTOS.stream().
                        filter(x->dto.getOutWarehousingOrderId().equals(x.getOutSubOrderId()))
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(out)){
                    List<OutWarehouseDetailDTO> outs = outMap.get(dto.getCarInfo());
                    if (CollectionUtils.isEmpty(outs)){
                        outMap.put(dto.getCarInfo(),out);
                    }else {
                        outs.addAll(out);
                        outMap.put(dto.getCarInfo(),outs);
                    }

                }
            }
        }
        //获取到车牌 -> 出入库详情
        List<AllocateOrderLogisticsInfoResponse> responses = Lists.newArrayList();

        //上面获取到了  车牌 -> 入库详情   车牌 -> 出库详情

        //收货 入库
        if (CollectionUtils.isNotEmpty(inMap.keySet())){
            for (String s : inMap.keySet()) {
                AllocateOrderLogisticsInfoResponse logisticsInfoResponse = new AllocateOrderLogisticsInfoResponse();
                logisticsInfoResponse.setCarNo(s);
                logisticsInfoResponse.setStatus("已收货");
                List<InWarehouseDetailDTO> inWarehouseDetailDTOList = inMap.get(s);
                List<AllocateOrderLogisticsInfoDTO> allocateOrderLogisticsInfoDTOS = Lists.newArrayList();
                //找入库明细;
                if (CollectionUtils.isNotEmpty(inWarehouseDetailDTOList)){
                    String createTime = inWarehouseDetailDTOList.get(0).getCreateTime();
                    AllocateOrderLogisticsInfoDTO allocateOrderLogisticsInfoDTO = new AllocateOrderLogisticsInfoDTO();
                    String codes = StringUtils.join(inWarehouseDetailDTOList.stream().map(InWarehouseDetailDTO::getCode).collect(Collectors.toList()), ",");
                    allocateOrderLogisticsInfoDTO.setInOrderNo(codes);
                    allocateOrderLogisticsInfoDTO.setStatus("已收货");
                    allocateOrderLogisticsInfoDTO.setTimeStr(createTime);
                    allocateOrderLogisticsInfoDTO.setTitle("入库单号:" + codes);
                    allocateOrderLogisticsInfoDTOS.add(allocateOrderLogisticsInfoDTO);
//                    StringUtils.join(inWarehouseDetailDTOList.stream().map(InWarehouseDetailDTO::get))
                }
                logisticsInfoResponse.setAllocateOrderLogisticsInfoList(allocateOrderLogisticsInfoDTOS);
                //获取到车牌 -> 入库明细数据
                responses.add(logisticsInfoResponse);
            }
        }

        //发货 出库明细
        if (CollectionUtils.isNotEmpty(outMap.keySet())){
            for (String s : outMap.keySet()) {
                //循环车牌  如果已经有返回的车牌了  那就设置对应车牌的 出库明细
                if (CollectionUtils.isNotEmpty(responses)){
                    List<AllocateOrderLogisticsInfoResponse> collect = responses.stream()
                            .filter(x -> s.equals(x.getCarNo())).collect(Collectors.toList());
                    List<AllocateOrderLogisticsInfoDTO> allocateOrderLogisticsInfoDTOS = Lists.newArrayList();
                    if (CollectionUtils.isNotEmpty(collect)){
                        AllocateOrderLogisticsInfoResponse logisticsInfoResponse = collect.get(0);
                        if (StringUtils.isBlank(logisticsInfoResponse.getStatus())){
                            logisticsInfoResponse.setStatus("已发货");
                        }
                        List<AllocateOrderLogisticsInfoDTO> infoList = logisticsInfoResponse.getAllocateOrderLogisticsInfoList();
                        List<OutWarehouseDetailDTO> outList = outMap.get(s);
                        if (CollectionUtils.isNotEmpty(outList)){
                            AllocateOrderLogisticsInfoDTO infoDTO = new AllocateOrderLogisticsInfoDTO();
                            String createTime = outList.get(0).getCreateTime();
                            infoDTO.setTimeStr(createTime);
                            String codes = StringUtils.join(outList.stream()
                                    .map(OutWarehouseDetailDTO::getCode).collect(Collectors.toList()),",");
                            infoDTO.setOutOrderNo(codes);
                            infoDTO.setStatus("已发货");
                            infoDTO.setTitle("出库单号:" + codes);
                            allocateOrderLogisticsInfoDTOS.add(infoDTO);
                        }
                        if (CollectionUtils.isNotEmpty(infoList)){
                            infoList.addAll(allocateOrderLogisticsInfoDTOS);
                        }else{
                            logisticsInfoResponse.setAllocateOrderLogisticsInfoList(allocateOrderLogisticsInfoDTOS);
                        }
                    }else {
                        //如果这个车牌不存在 那就新放入一个车牌
                        AllocateOrderLogisticsInfoResponse logisticsInfoResponse = new AllocateOrderLogisticsInfoResponse();
                        logisticsInfoResponse.setCarNo(s);
                        if (StringUtils.isBlank(logisticsInfoResponse.getStatus())){
                            logisticsInfoResponse.setStatus("已发货");
                        }
                        List<OutWarehouseDetailDTO> outList = outMap.get(s);
                        if (CollectionUtils.isNotEmpty(outList)){
                            AllocateOrderLogisticsInfoDTO infoDTO = new AllocateOrderLogisticsInfoDTO();
                            String createTime = outList.get(0).getCreateTime();
                            infoDTO.setTimeStr(createTime);
                            String codes = StringUtils.join(outList.stream()
                                    .map(OutWarehouseDetailDTO::getCode).collect(Collectors.toList()),",");
                            infoDTO.setOutOrderNo(codes);
                            infoDTO.setStatus("已发货");
                            infoDTO.setTitle("出库单号:" + codes);
                            allocateOrderLogisticsInfoDTOS.add(infoDTO);
                            logisticsInfoResponse.setAllocateOrderLogisticsInfoList(allocateOrderLogisticsInfoDTOS);
                            responses.add(logisticsInfoResponse);
                        }

                    }
                }else {
                    // 如果没有入库  放进去新车牌
                    AllocateOrderLogisticsInfoResponse logisticsInfoResponse = new AllocateOrderLogisticsInfoResponse();
                    logisticsInfoResponse.setCarNo(s);
                    if (StringUtils.isBlank(logisticsInfoResponse.getStatus())){
                        logisticsInfoResponse.setStatus("已发货");
                    }
//                    List<AllocateOrderLogisticsInfoDTO> infoList = logisticsInfoResponse.getAllocateOrderLogisticsInfoList();
                    List<OutWarehouseDetailDTO> outList = outMap.get(s);
                    List<AllocateOrderLogisticsInfoDTO> allocateOrderLogisticsInfoDTOS = Lists.newArrayList();
                    if (CollectionUtils.isNotEmpty(outList)){
                        AllocateOrderLogisticsInfoDTO infoDTO = new AllocateOrderLogisticsInfoDTO();
                        String createTime = outList.get(0).getCreateTime();
                        infoDTO.setTimeStr(createTime);
                        String codes = StringUtils.join(outList.stream()
                                .map(OutWarehouseDetailDTO::getCode).collect(Collectors.toList()),",");
                        infoDTO.setOutOrderNo(codes);
                        infoDTO.setStatus("已发货");
                        infoDTO.setTitle("出库单号:" + codes);
                        allocateOrderLogisticsInfoDTOS.add(infoDTO);
                        logisticsInfoResponse.setAllocateOrderLogisticsInfoList(allocateOrderLogisticsInfoDTOS);
                        responses.add(logisticsInfoResponse);
                    }
                }
            }
        }

        if (CollectionUtils.isNotEmpty(responses)){
            for (AllocateOrderLogisticsInfoResponse r : responses) {
                List<InAndOutOfWarehouseOrderDTO> collect = warehouseOrderDTOS.stream().filter(x -> Objects.equals(x.getCarInfo(), r.getCarNo()))
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(collect)){
                    r.setDriver(collect.get(0).getDriver());
//                    r.setStatus();
                    r.setPhone(collect.get(0).getPhone());
                }
                if (CollectionUtils.isNotEmpty(r.getAllocateOrderLogisticsInfoList())){
                    r.setAllocateOrderLogisticsInfoList(r.getAllocateOrderLogisticsInfoList().stream().
                            sorted(Comparator.comparing(AllocateOrderLogisticsInfoDTO::getStatus).reversed()).collect(Collectors.toList()));
                }
            }
        }
        return responses;

    }

//    //获取出入
//    public static  List<InAndOutOfWarehouseOrderDTO> getInAndOutOfWarehouseOrderDTOS(Object wmsOrder){
//        if (wmsOrder == null){
//            return null;
//        }
//        JSONObject result = JSON.parseObject(JSON.toJSONString(wmsOrder));
//        if (result == null){
//            return null;
//        }
//        result = result.getJSONObject("result");
//        if (result == null){
//            return null;
//        }
//        JSONArray array = result.getJSONArray("warehousingOrders");
//        List<InAndOutOfWarehouseOrderDTO> list = Lists.newArrayList();
//        if (array != null && array.size() > 0){
//            for (int i =0;i<array.size();i++){
//                JSONObject obj = array.getJSONObject(i);
//                if (obj == null)continue;
//                InAndOutOfWarehouseOrderDTO dto = new InAndOutOfWarehouseOrderDTO();
//                String orderStatus = obj.getString("orderStatus");
//                if ("2.0".equals(orderStatus) || "2".equals(orderStatus)){
//                    dto.setStatusDesc("完成");
//                }else if ("-1.0".equals(orderStatus) || "1.0".equals(orderStatus)){
//                    dto.setStatusDesc("取消");
//                }
//                dto.setTotalQuantity(obj.getString("sumQuantity"));
//                dto.setCode(obj.getString("warehousingOrderId"));
//                dto.setOutCode(obj.getString("sourceWarehousingOrderId"));
////                dto.setCreateTime(TimeUtil.parseTime(obj.getString("createTime")));
//                dto.setCreateTime(TimeUtil.parseSimpleDateFormat(obj.getString("createTime")));
//                dto.setCompleteTime(TimeUtil.parseSimpleDateFormat(obj.getString("postingTime")));
//                dto.setCarInfo(obj.getString("shipNo"));
//                dto.setPhone(obj.getString("shipPhone"));
//                dto.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(obj.getString("expectedDate")));
//                list.add(dto);
//            }
//        }
//        return list;
//
//    }

    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-029")
    public Result<List<AllocateOrderDocumentLogDTO>> getDocumentLog(AllocateOrderQueryDocumentLogReques allocateOrderQueryDocumentLogReques) {
        log.info("AllocateOrderReadServiceImpl.getDocumentLog.request:{}", JSON.toJSONString(allocateOrderQueryDocumentLogReques));

        OperateQueryInfoRequest operateQueryInfoRequest = new OperateQueryInfoRequest();
        AllocateOrderRequest request = new AllocateOrderRequest();
        request.setAllocateOrderCode(allocateOrderQueryDocumentLogReques.getAllocateApplyOrderCode());
        AllocateOrderWithOrderDetailsSDO sdo = allocateOrderReadRepository.get(request);
        //操作者类型
//        operateQueryInfoRequest.setOperatorType(OperatorType.USER.getOperatorType());
        //模块ID 1: 主数据  2:月度计划 3：调拨一盘货 4：预报销售 5：价格  6：活动
        operateQueryInfoRequest.setModuleId("3");
        //模块名称 必传
        operateQueryInfoRequest.setModuleName(ModuleEnum.UNIFIED_INVENTORY.getModuleName());
        //对象名称 查询字段和查询对象二选一
        operateQueryInfoRequest.setObjectName(allocateOrderQueryDocumentLogReques.getAllocateApplyOrderCode());
        //对象ID 如果是对象，填写对象 ID；如果是字段，填写字段的值 前端传
        if (sdo != null && sdo.getAllocateOrderSDO() != null && sdo.getAllocateOrderSDO().getId() != null) {
            operateQueryInfoRequest.setObjectId(sdo.getAllocateOrderSDO().getId().toString());
        }
        //object必传
        if (StringUtils.isBlank(operateQueryInfoRequest.getObjectId())) {
            return Result.success(Lists.newArrayList());
        }
//        operateQueryInfoRequest.setObjectId(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getId().toString());
        //数据类型 1：字段类型  2：对象类型
        //使用com.alibaba.cz.base.tool.log.model.OpLogDateTypeEnum中的枚举值
        operateQueryInfoRequest.setDataType(OpLogDateTypeEnum.OBJECT_TYPE.getDataType());
        //是否需要返回新老值
        operateQueryInfoRequest.setNeedReturnNewOldValue(true);
        //起始索引
        operateQueryInfoRequest.setStart(0);
        //页面大小
        operateQueryInfoRequest.setLimit(MAX_PAGE_SIZE);
        //获取操作不同
        Result<List<OperateLogDiff>> listResult = queryOperateLogService.queryOperateLogRowDiff(operateQueryInfoRequest);
        List<AllocateOrderDocumentLogDTO> allocateOrderDocumentLogDTOS = Lists.newArrayList();
        if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())) {
            List<OperateLogDiff> operateLogList = listResult.getResult();
            for (OperateLogDiff operateLogDiff : operateLogList) {
                if (EnumUtils.exclude(operateLogDiff.getOperateType())) {
                    continue;
                }
                    AllocateOrderDocumentLogDTO dto = new AllocateOrderDocumentLogDTO();
                    dto.setGmtCreate(operateLogDiff.getGmt_create());
                    dto.setOperationType(EnumUtils.getAllocateApplyOrderOperationTypeEnum(operateLogDiff.getOperateType()));
                    dto.setOperator(InfoUtil.getRealName(operateLogDiff.getOperatorId()));
                    String features = operateLogDiff.getFeatures();
                    if (StringUtils.isNotBlank(features)) {
                        Map<String, String> map = JSONObject.parseObject(features, Map.class);
                        if (MapUtils.isNotEmpty(map)) {
                            String content = (UNKNOWN.equals(map.get("name")) ? SYSTEM : map.get("name")) + " " + map.get("active") + "了" + map.get("orderType") + "单(" + map.get("bizNo") + ");状态:" + map.get("status");
                            dto.setOperator(content);
                        }
                    }

//                for (RowDiff rowDiff:diffs){
//                    if (Objects.nonNull(rowDiff)&&"scItemCode".equals(rowDiff.getFieldName())){
//                        scItemCodeRows.add(rowDiff);
//                    }
//                }
//                RowDiff scItemCodeRow = null;
//                if (CollectionUtils.isNotEmpty(scItemCodeRows)){
//                    scItemCodeRow = scItemCodeRows.get(0);
//                }
//                List<RowDiff> quantityRows = diffs.stream().filter(x-> "quantity".equalsIgnoreCase(x.getFieldName())).collect(Collectors.toList());
//                RowDiff quantityRow = null;
//                if (CollectionUtils.isNotEmpty(quantityRows)){
//                    quantityRow = quantityRows.get(0);
//                }
//
//                if (scItemCodeRow != null && quantityRow != null){
//                    s.add(scItemCodeRow.getNewValue() + ":" + quantityRow.getOldValue() + " -> " +  quantityRow.getNewValue() );
////                    String opt = OperateType
//                }
                    allocateOrderDocumentLogDTOS.add(dto);
//                String getScItemCode = diffs.stream()
//                for (RowDiff rowDiff : diffs){
//                    if ("scItemCode".equalsIgnoreCase(rowDiff.getFieldName())){
//                        rowDiff.getOldValue() + " -> " + rowDiff.getNewValue();
//                    }
//                    System.out.println(JSON.toJSONString(rowDiff));
//                }
                }

            }
            log.info("AllocateOrderReadServiceImpl.getDocumentLog.result:{}", JSON.toJSONString(allocateOrderDocumentLogDTOS));

            return Result.success(allocateOrderDocumentLogDTOS);
        }

    @Override
    public Result<List<AllocateOrderCheckLogisticsResponse>> checkLogistics(AllocateOrderGetLogisticsInfoRequest allocateOrderGetLogisticsInfoRequest) {
        log.info("AllocateOrderReadServiceImpl.checkLogistics.request:{}",JSON.toJSONString(allocateOrderGetLogisticsInfoRequest));

        List<AllocateOrderCheckLogisticsResponse> responses = Lists.newArrayList();

            Result<List<AllocateOrderLogisticsInfoResponse>> logisticsInfo = getLogisticsInfo(allocateOrderGetLogisticsInfoRequest);
            log.info("AllocateOrderReadServiceImpl.checkLogistics.getLogisticsInfo.result:{}", JSON.toJSONString(logisticsInfo));

            if (logisticsInfo != null && CollectionUtils.isNotEmpty(logisticsInfo.getResult())) {
                for (AllocateOrderLogisticsInfoResponse response : logisticsInfo.getResult()) {
                    AllocateOrderCheckLogisticsResponse checkResponse = new AllocateOrderCheckLogisticsResponse();
                    //车牌
                    checkResponse.setText(response.getCarNo());
                    checkResponse.setDeliveryStateDesc(response.getStatus());
                    List<AllocateOrderCheckLogisticsInfoDTO> list = Lists.newArrayList();
                    for (AllocateOrderLogisticsInfoDTO dto : response.getAllocateOrderLogisticsInfoList()) {
                        AllocateOrderCheckLogisticsInfoDTO logisticsInfoDTO = new AllocateOrderCheckLogisticsInfoDTO();
                        logisticsInfoDTO.setTime(dto.getTimeStr());
                        StringBuffer sb = new StringBuffer();
                        if (StringUtils.isNotBlank(dto.getStatus())) {
                            sb.append(dto.getStatus()).append(" ");
                        }
                        //现在不要求出入库单号显示
//                    if (StringUtils.isNotBlank(dto.getTitle())){
//                        sb.append(dto.getTitle());
//                    }
                        logisticsInfoDTO.setPackageInfo(sb.toString());
                        list.add(logisticsInfoDTO);
                    }
                    //倒序拍一下
//                if (CollectionUtils.isNotEmpty(list)){
//                    Collections.reverse(list);
//                }
                    checkResponse.setDeliveryInfos(list);
                    responses.add(checkResponse);
                }
            }
            if (CollectionUtils.isNotEmpty(responses)) {
                responses.add(new AllocateOrderCheckLogisticsResponse());
            }


//        for(int i =0;i<2;i++){
//            AllocateOrderCheckLogisticsResponse response = new AllocateOrderCheckLogisticsResponse();
//            AllocateOrderCheckLogisticsInfoDTO dto = new AllocateOrderCheckLogisticsInfoDTO();
//            dto.setTime("2021-12-03 15:23:00");
//            dto.setPackageInfo("出入单号abcd");
//            AllocateOrderCheckLogisticsInfoDTO dto2 = new AllocateOrderCheckLogisticsInfoDTO();
//            dto2.setTime("2021-12-31 12:12:12");
//            dto2.setPackageInfo("入库单号:啊哈哈哈哈");
//            List<AllocateOrderCheckLogisticsInfoDTO> dtos = Lists.newArrayList();
//            dtos.add(dto);
//            dtos.add(dto2);
//            response.setDeliveryInfos(dtos);
//            response.setType("物流系");
//            response.setText("啊啊哈哈哈");
//            response.setDeliveryStateDesc("描述");
//            responses.add(response);
//        }
            log.info("AllocateOrderReadServiceImpl.checkLogistics.result:{}", JSON.toJSONString(responses));

            return Result.success(responses);
        }


        /**
         * 用来给发票退单调用
         * @param allocateOrderDetailSearchRequest
         * @return
         */
        @Override
        public Result<List<AllocateOrderDetailVO>> searchData (AllocateOrderDetailSearchRequest
        allocateOrderDetailSearchRequest){
            AllocateOrderDetailSearchRequest request = allocateOrderDetailSearchRequest;
            handleSearchConditions(request);
//        Map<String, String> wmsMap1 = InfoUtil.getWmsMap(null);
//        Result<List<OuiAllocateOrderDetailIndex>> result = detailIndexService.search(request);
            Result<List<OuiAllocateOrderDetailIndex>> result = detailIndexService.get(request);
//        Result<Long> count = detailIndexService.getCount(request);
            List<AllocateOrderDetailVO> detailVOS = Lists.newArrayList();
            if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
                Set<String> subAllocateOrderIds = new HashSet<>();
                //预报单id
                Set<String> allocateApplyOrderIds = new HashSet<>();

                //调拨单id
                Set<String> stoOrderIds = new HashSet<>();
                for (OuiAllocateOrderDetailIndex index : result.getResult()) {
                    if (StringUtils.isNotEmpty(index.getMainAllocateApplyOrderId())) {
                        allocateApplyOrderIds.add(index.getMainAllocateApplyOrderId());
                    }
                    stoOrderIds.add(index.getMainCode());
                    subAllocateOrderIds.add(String.valueOf(index.getSubAllocateOrderId()));
                }

                //客户、客户地址数据，做成弱依赖
                Map<String, String> orgMap = Maps.newHashMap();
                try {
                    orgMap = getOrgMap(result);
                } catch (Throwable e) {
                    log.error("AllocateOrderReadServiceImpl.enrichInfo.getOrgMapInfo error", e);
                }
                //仓库
                Map<String, WmsSDO> wmsMap = Maps.newHashMap();
                try {
                    wmsMap = getWmsMap(result);
                } catch (Throwable e) {
                    log.error("AllocateOrderReadServiceImpl.enrichInfo.getWmsMapInfo error", e);
                }
//            //客户 addressCode->customer
//            Map<String, AllocateOrderGetCustomerResponse> customerResponseMap = Maps.newHashMap();
//            try {
//                customerResponseMap = getCustomerResponseMap(result);
//            } catch (Throwable e) {
//                log.error("AllocateOrderReadServiceImpl.enrichInfo.getCustomerInfo error", e);
//            }
//            //客户 customerCode -> customer
//            Map<String, AllocateOrderGetCustomerResponse> customerCodeMap = Maps.newHashMap();
//            try {
//                customerCodeMap = getCustomerMapByCustomerCodeFromMap(customerResponseMap);
//            } catch (Throwable e) {
//                log.error("AllocateOrderReadServiceImpl.enrichInfo.getCustomerCodeInfo error", e);
//            }
//            //branchCustomerCodeMap
//            Map<String, AllocateOrderGetCustomerResponse> branchCustomerMap = Maps.newHashMap();
//            try {
//                branchCustomerMap = getBranchCustomerMap(result);
//            } catch (Throwable e) {
//                log.error("AllocateOrderReadServiceImpl.enrichInfo.getBranchCustomerInfo error", e);
//            }

                //商品
                Map<String, AllocateOrderDetailBatchGetScItemResponse> scItemResponseMap = Maps.newHashMap();
                try {
                    scItemResponseMap = getScItemResponseMap(result);
                } catch (Throwable e) {
                    log.error("AllocateOrderReadServiceImpl.enrichInfo.getScItemInfo error", e);
                }
//            //出入库单明细
//            Map<String, List<OutWarehouseDetailDTO>> inOutResponseMap = Maps.newHashMap();
//            try {
//                inOutResponseMap = getInOutResponseMap(subAllocateOrderIds);
//            } catch (Throwable e) {
//                log.error("AllocateOrderReadServiceImpl.enrichInfo.getInOutInfo error", e);
//            }
//            //出库单
//            Map<String, List<InAndOutOfWarehouseOrderDTO>> wmsOrdersMap = Maps.newHashMap();
//            try {
//                wmsOrdersMap = getWmsOrders(subAllocateOrderIds);
//            } catch (Throwable e) {
//                log.error("AllocateOrderReadServiceImpl.enrichInfo.getWmsOrderInfo error", e);
//            }

                //预报单
                Map<String, AllocateApplyOrder> allocateApplyOrderMap = queryAllocateApplyOrderMap(new ArrayList<>(allocateApplyOrderIds));
                //交货单
//            Map<String, String> consignmentOrderMap = queryConsignmentOrderNumMap(new ArrayList<>(stoOrderIds));
//            Map<String, String> consignmentOrderMap = getConsignmentOrderMap(Lists.newArrayList(stoOrderIds));

                for (OuiAllocateOrderDetailIndex index : result.getResult()) {
                    AllocateOrderDetailVO detailVO = new AllocateOrderDetailVO();
                    detailVO.setType(index.getSubType() == null ? null : index.getSubType().intValue());
                    detailVO.setTypeDesc(InfoUtil.getTypeDesc(index.getSubType() == null ? null : index.getSubType().intValue()));
                    detailVO.setCode(index.getMainCode());
                    detailVO.setOutAllocateOrderId(index.getMainOutAllocateOrderId());
                    detailVO.setAllocateApplyOrderCode(index.getMainAllocateApplyOrderCode());
                    detailVO.setLineNo(index.getSubLineNo() == null ? null : index.getSubLineNo().toString());
                    detailVO.setOutAllocateOrderLineId(index.getSubOutAllocateOrderLineId());
                    detailVO.setAllocateApplyOrderLineId(index.getSubAllocateApplyOrderLineId());
                    detailVO.setApplyOrgId(index.getMainApplyOrgId());
                    //TODO 看是否冗余
                    // TODO: 2021/12/2 余红伟，不要写魔法变量，货品组是固定的11？如果是其他货品组？
                    detailVO.setApplyOrgName(orgMap.get(index.getMainApplyOrgId()));
                    detailVO.setProductGroup("11");
                    detailVO.setProductGroupDesc("常温");
                    detailVO.setStatus(index.getMainStatus() == null ? null : index.getMainStatus().intValue());
                    detailVO.setStatusDesc(InfoUtil.getStatusEpochDesc(index.getMainStatus() == null ? null : index.getMainStatus().intValue()));
                    detailVO.setStatusStr(InfoUtil.getStatusDesc(index.getMainStatus() == null ? null : index.getMainStatus().intValue()));
                    detailVO.setIsDTC(Objects.equals(index.getMainIsDTC(), 1L) ? true : false);
                    detailVO.setIsDTCDesc(Objects.equals(index.getMainIsDTC(), 1L) ? "是" : "否");
                    detailVO.setReturnOrder(InfoUtil.getBoolean(index.getMainReturnOrder()));
                    detailVO.setReturnOrderDesc(InfoUtil.getBooleanDesc(index.getMainReturnOrder()));
                    //TODO 仓库 收发组织
                    detailVO.setReceiveAreaId(index.getMainReceiveAreaId());
                    WmsSDO receiveWmsSDO = wmsMap.get(index.getMainReceiveAreaId());
                    if (receiveWmsSDO != null) {
                        detailVO.setReceiveAreaName(receiveWmsSDO.getName());
                    }
                    WmsSDO receiveWarehouseWmsSDO = wmsMap.get(index.getMainReceiveWarehouseId());
                    if (receiveWarehouseWmsSDO != null) {
                        detailVO.setReceiveWarehouseName(receiveWarehouseWmsSDO.getName());
                    }
                    detailVO.setReceiveOrgId(index.getMainReceiveOrgId());
                    detailVO.setReceiveOrgName(orgMap.get(index.getMainReceiveOrgId()));
                    detailVO.setShipAreaId(index.getMainShipAreaId());
                    detailVO.setShipOrgId(index.getMainShipOrgId());
                    detailVO.setShipOrgName(orgMap.get(index.getMainShipOrgId()));
                    WmsSDO shipWmsSDO = wmsMap.get(index.getMainShipAreaId());
                    if (shipWmsSDO != null) {
                        detailVO.setShipAreaName(shipWmsSDO.getName());
                    }
                    WmsSDO shipWarehouseWmsSDO = wmsMap.get(index.getMainShipWarehouseId());
                    if (shipWarehouseWmsSDO != null) {
                        detailVO.setShipWarehouseName(shipWarehouseWmsSDO.getName());
                    }
                    // 客户编码
                    detailVO.setCustomer(index.getMainCustomer());
                    //TO
//                AllocateOrderGetCustomerResponse customerResponse = customerResponseMap.get(index.getMainAddressCode());
//                if (customerResponse != null) {
//                    detailVO.setCustomerName(customerResponse.getCustomerName());
//                    detailVO.setCustomerAddress(customerResponse.getCustomerAddress());
//                    detailVO.setCustomerAddressName(customerResponse.getCustomerAddressName());
//                }
                    //TODO 物流信息
                    detailVO.setLogisticsInfo(null);
                    detailVO.setLineStatusDesc(InfoUtil.getStatusEpochDesc(index.getSubStatus() == null ?
                            null : index.getSubStatus().intValue()));
                    detailVO.setLineStatusStr(InfoUtil.getStatusDesc(index.getSubStatus() == null ? null : index.getSubStatus().intValue()));
//                detailVO.setStatus(index.getMainStatus()==null?null:index.getMainStatus().intValue());
//                detailVO.setStatusDesc(InfoUtil.getStatusEpochDesc(detailVO.getStatus()));

                    detailVO.setScItemId(index.getSubScItemId());
                    detailVO.setScItemCode(index.getSubScItemCode());
                    AllocateOrderDetailBatchGetScItemResponse scItemResponse = scItemResponseMap.get(index.getSubScItemId());
                    if (scItemResponse != null) {
                        detailVO.setScItemName(scItemResponse.getTitle());
                        if (StringUtils.isBlank(detailVO.getScItemCode())) {
                            detailVO.setScItemCode(scItemResponse.getScItemCode());
                        }
                    }
                    detailVO.setShipMethodDesc(InfoUtil.getShipMethodDesc(index.getMainShipMethod() == null ? null :
                            index.getMainShipMethod().intValue()));
                    detailVO.setQuantity(InfoUtil.handleQuantityDate(index.getSubQuantity()));
                    if (Objects.equals(Boolean.TRUE, InfoUtil.getBoolean(index.getMainReturnOrder()))) {
                        detailVO.setConfirmQuantity(InfoUtil.handleQuantityDate(index.getSubQuantity()));
                    } else {
                        detailVO.setConfirmQuantity(InfoUtil.handleQuantityDate(index.getSubConfirmQuantity()));
                    }
                    //  交货数量 取值交货单更新
                    detailVO.setDeliveryQuantity(index.getSubDeliveryQuantity());
                    detailVO.setShipQuantity(index.getSubShipQuantity() == null ? null : index.getSubShipQuantity().toString());
                    //es没有收货数量
                    detailVO.setReceiveQuantity(index.getSubReceiveQuantity() == null ? null : index.getSubReceiveQuantity().toString());
                    detailVO.setNotIssuedQuantity(InfoUtil.handleQuantityDate(InfoUtil.subtract(index.getSubQuantity(), index.getSubShipQuantity())));
                    detailVO.setTransQuantity(InfoUtil.subtract(index.getSubShipQuantity(), index.getSubReceiveQuantity()));
                    //es没有赠送数量
                    detailVO.setGiftQuantity(index.getSubGiftQuantity());
                    detailVO.setUnit(index.getSubUnit());
                    detailVO.setPrice(index.getSubPrice());
                    detailVO.setDiscountPrice(InfoUtil.getDiscountPrice(index.getSubSubTotalAmount(), index.getSubQuantity()));
                    detailVO.setAmount(InfoUtil.multiply(index.getSubPrice(), index.getSubQuantity()));
                    //结算金额
                    detailVO.setCrossCompanySettlement(index.getSubExchangeAmt());
                    //这个地方得保证 折后金额和小计金额的一致性.
                    detailVO.setDiscountAmt(index.getSubDiscountAmount());
                    //TODO 交货金额哪里来.
                    detailVO.setDeliveryAmt(InfoUtil.multiply(index.getSubPrice(), index.getSubDeliveryQuantity()));
                    detailVO.setDeliveryDiscountAmt(InfoUtil.multiply(detailVO.getDiscountPrice(), index.getSubDeliveryQuantity()));
                    detailVO.setShippedDiscountAmt(InfoUtil.multiply(index.getSubShipQuantity() == null ? null : index.getSubShipQuantity().toString(), detailVO.getDiscountPrice()));
                    ;
                    detailVO.setShippedAmt(InfoUtil.multiply(index.getSubShipQuantity() == null ? null : index.getSubShipQuantity().toString(), index.getSubPrice()));
                    detailVO.setTaxRate(index.getSubTaxRate());
                    detailVO.setExpectedProductDate(TimeUtil.getDateByLong(index.getSubExpectedProduceDate()));
                    detailVO.setExpectedProductDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getExpectedProductDate()));
                    detailVO.setExpectedDeliveryDate(TimeUtil.getDateByLong(index.getMainExpectedDeliveryDate()));
                    detailVO.setExpectedDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getExpectedDeliveryDate()));
                    detailVO.setLineExpectedDeliveryDate(TimeUtil.getDateByLong(index.getSubExpectedDeliveryDate()));
                    detailVO.setLineExpectedDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getLineExpectedDeliveryDate()));
                    detailVO.setSendBackRequired(InfoUtil.getBoolean(index.getMainSendBackRequired()));
                    detailVO.setSendBackRequiredDesc(InfoUtil.getBooleanDesc(index.getMainSendBackRequired()));
                    detailVO.setCloseReason(index.getSubCloseReason());
                    detailVO.setCloseDesc(InfoUtil.getBooleanDesc(index.getSubClose()));
                    detailVO.setClosed(InfoUtil.getBoolean(index.getSubClose()));
                    detailVO.setLineRemark(index.getSubRemarks());
                    // TODO 这个和期待生产日期的区别  暂时没有
                    detailVO.setProductDate(TimeUtil.getDateByLong(index.getSubExpectedProduceDate()));
                    detailVO.setProductDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getProductDate()));
                    //TODO 出库生产日期是  出入库单的生产日期 多值 逗号
                    detailVO.setOutWarehouseProductDate(null);
                    //时间直接使用gmt了.
//                detailVO.setCreateTime(index.getMainCreateTime()==null?InfoUtil.getDate(index.getMainGmtCreate()):InfoUtil.getDate(index.getMainCreateTime()));
                    detailVO.setCreateTime(InfoUtil.getDate(index.getMainGmtCreate()));
                    //确认日期是 确认数量变化的时间 sap找sap 回复创建调拨单时间
                    detailVO.setConfirmDate(TimeUtil.getIgnoreNullDateByLong(index.getSubConfirmTime()));
                    detailVO.setConfirmDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getConfirmDate()));
                    // 交货日期
                    if (index.getSubDeliveryDate() != null && index.getSubDeliveryDate() == new Date(0).getTime()) {
                        detailVO.setDeliveryDate(null);
                    } else {
                        detailVO.setDeliveryDate(TimeUtil.getDateByLong(index.getSubDeliveryDate()));
                    }
//                detailVO.setDeliveryDate(TimeUtil.getDateByLong(index.getSubDeliveryDate()));
                    detailVO.setDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getDeliveryDate()));
                    //TODO 出库日期 ? 发货时间
                    detailVO.setShipTime(TimeUtil.getIgnoreNullDateByLong(index.getSubShipTime()));
                    detailVO.setShipTimeStr(TimeUtil.formatYYYY_MM_dd(detailVO.getShipTime()));
                    detailVO.setOutWarehouseDate(null);
//                detailVO.setReceiveDate(null);
                    detailVO.setReceiveTime(TimeUtil.getIgnoreNullDateByLong(index.getSubReceiveTime()));
                    detailVO.setReceiveTimeStr(TimeUtil.formatYYYY_MM_dd(detailVO.getReceiveTime()));
                    if (receiveWarehouseWmsSDO != null) {
                        detailVO.setReceiveAreaContactor(receiveWarehouseWmsSDO.getContactPerson());
                        detailVO.setReceiveAreaPhone(receiveWarehouseWmsSDO.getPhone());
                        detailVO.setReceiveAreaAddress(receiveWarehouseWmsSDO.getAddress());
                    }
                    //TODO 单据日期的写入 需要再看
                    detailVO.setDocDate(InfoUtil.getDate(index.getMainDocDate()));
                    detailVO.setDocDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getDocDate()));
                    //TODO 生效日期
                    detailVO.setBeginDate(null);
                    detailVO.setLineExpectedDeliveryDate(InfoUtil.getDate(index.getSubExpectedDeliveryDate()));
                    detailVO.setLineExpectedDeliveryDateStr(TimeUtil.formatYYYY_MM_dd(detailVO.getLineExpectedDeliveryDate()));
//                detailVO.setCreator(NameUtil.getRealName(index.getMainCreator()));

                    detailVO.setCreator(InfoUtil.getRealName(index.getMainCreator()));
                    //detailVO.setCreator(InfoUtil.getRealName(index.getSubCreator()));
                    detailVO.setCreateTime(InfoUtil.getDate(index.getMainGmtCreate()));
                    //TODO 提交时间
                    detailVO.setSubmitTime(InfoUtil.getDate(index.getMainSubmitTime()));
//                detailVO.setUpdator(NameUtil.getRealName(index.getMainUpdater()));
                    detailVO.setUpdator(InfoUtil.getRealName(index.getMainUpdater()));
                    detailVO.setUpdateTime(InfoUtil.getDate(index.getMainGmtModified()));
                    detailVO.setRemark(index.getMainRemark());
                    detailVO.setOrderReasonDesc(EnumUtils.getOrderReason(index.getMainOrderReason()));
                    //判断仓库是否有值
                    if (Objects.nonNull(receiveWmsSDO)) {
                        detailVO.setSapInternalSalesBPCode(receiveWmsSDO.getSapInternalSalesBPCode());
                        detailVO.setSapInternalDeliveryBPCode(receiveWmsSDO.getSapInternalDeliveryBPCode());
                        detailVO.setSapSalesBPCode(receiveWmsSDO.getSapSalesBPCode());
                        detailVO.setSapDeliveryBPCode(receiveWmsSDO.getSapDeliveryBPCode());
                        if (Objects.equals(index.getMainType() == null ? null : index.getMainType().intValue(),
                                AllocateOrderTypeEnum.HEADQUARTER_SALES.getType().intValue())) {
                            detailVO.setSapCustomer(receiveWmsSDO.getSapSalesBPCode());
                            detailVO.setSapCustomerAddress(receiveWmsSDO.getSapDeliveryBPCode());
                        }
                    }
                    //详细地址
                    if (receiveWarehouseWmsSDO != null && StringUtils.isNotBlank(receiveWarehouseWmsSDO.getAddress())
                            && Objects.equals(index.getMainType() == null ? null : index.getMainType().intValue(),
                            AllocateOrderTypeEnum.HEADQUARTER_SALES.getType().intValue())) {
                        detailVO.setSapCustomerAddress(receiveWarehouseWmsSDO.getAddress());
                    }


                    detailVO.setSapCostCenter(index.getMainSapCostCenter());
                    detailVO.setSapRefPoNo(index.getMainSapRefPoNo());
                    detailVO.setSapSalesOrgId(index.getMainSapSalesOrgId());
                    detailVO.setSapChannel(index.getMainSapChannel());
                    detailVO.setUnit(InfoUtil.convertUnit(index.getSubUnit()));
                    detailVO.setMessage(index.getMainMessage());
                    detailVO.setBranchCustomersCode(index.getMainBranchCustomersCode());


                    //外部调拨预报单号
                    AllocateApplyOrder allocateApplyOrder = allocateApplyOrderMap.get(index.getMainAllocateApplyOrderId());
                    if (Objects.nonNull(allocateApplyOrder)) {
                        detailVO.setOutAllocateApplyOrderId(allocateApplyOrder.getOutAllocateApplyOrderId());
                    }
                    //交货单号
//                if (StringUtils.isNotEmpty(detailVO.getCode())){
//                    detailVO.setDeliveryOrderNo(consignmentOrderMap.get(detailVO.getCode()));
//                }
//                if (StringUtils.isNoneBlank(detailVO.getCode(), detailVO.getScItemId())) {
//                    detailVO.setDeliveryOrderNo(consignmentOrderMap.get(detailVO.getCode() + "," + detailVO.getScItemId()));
//                }
                    //确认未发货数量 确认未发量】=确认数量 confirmQuantity-收货数量 receiveQuantity-在途数量 transQuantity
                    if (StringUtils.isNotEmpty(detailVO.getConfirmQuantity())) {
                        Integer receiveQuantity = 0;
                        Integer transQuantity = 0;
                        if (StringUtils.isNotEmpty(detailVO.getReceiveQuantity())) {
                            receiveQuantity = Integer.valueOf(detailVO.getReceiveQuantity());
                        }
                        if (StringUtils.isNotEmpty(detailVO.getTransQuantity())) {
                            transQuantity = Integer.valueOf(detailVO.getTransQuantity());
                        }
                        Integer confirmQuantity = Integer.valueOf(detailVO.getConfirmQuantity()) - receiveQuantity - transQuantity;
                        detailVO.setConfirmUndeliveredQuantity(confirmQuantity.toString());
                    }
                    //未确认数量 未确认数量=订单数量 quantity -确认数量 confirmQuantity
                    if (StringUtils.isNotEmpty(detailVO.getQuantity())) {
                        Integer confirmQuantity = 0;
                        if (StringUtils.isNotEmpty(detailVO.getConfirmQuantity())) {
                            confirmQuantity = Integer.valueOf(detailVO.getConfirmQuantity());
                        }
                        Integer unconfirmedQuantity = Integer.valueOf(detailVO.getQuantity()) - confirmQuantity;
                        detailVO.setUnconfirmedQuantity(unconfirmedQuantity.toString());
                    }


//                AllocateOrderGetCustomerResponse branch = branchCustomerMap.get(index.getMainBranchCustomersCode());
//                if (branch != null) {
//                    detailVO.setBranchCustomersName(branch.getCustomerName());
//                }
                    if (receiveWarehouseWmsSDO != null &&
                            StringUtils.isNotBlank(receiveWarehouseWmsSDO.getAddress()) &&
                            Objects.equals(index.getMainType() == null ? null : index.getMainType().intValue(),
                                    AllocateOrderTypeEnum.HEADQUARTER_SALES.getType().intValue())) {
                        detailVO.setSapCustomerAddressName(receiveWarehouseWmsSDO.getAddress());
                    }
                    detailVOS.add(detailVO);
                }
            }
            Result<List<AllocateOrderDetailVO>> success = Result.success(detailVOS);
            return success;
        }
        @Override
        @FacadeInvoker
        public Result<SurplusAllocateQuantityResponse> collectAllocateOrderQuantity (CollectAllocateOrderQuantityRequest
        collectAllocateOrderQuantityRequest){

            /**
             * 组合参数
             * 检索区间为当月1号00:00:00 到当月最后一天 23:59:59
             * scItemCode 为商品ID
             * orgIdList 为当前登录人所属分子公司下到所有层级
             */
            long startTime = DateUtils.obtainCurrentDayBeginOrEnd(DateUtils.getStartTimeOfMonth(), true).getTime();
            long endTime = DateUtils.obtainCurrentDayBeginOrEnd(DateUtils.getLastTimeOfMonth(), false).getTime();
            String scItemCode = collectAllocateOrderQuantityRequest.getScItemCode();

            IdQueryRequest idQueryRequest = new IdQueryRequest();
            idQueryRequest.setId(collectAllocateOrderQuantityRequest.getApplyOrgId());
            idQueryRequest.setType(OrganizationTypeEnum.SALES_DEPARTMENT.getCode());
            // 查询分子公司下所有层级
            List<String> orgIdList = organizationQueryService.queryAllChildOrganizationToTargetType(idQueryRequest).getResult().stream().map(e -> e.getId()).collect(Collectors.toList());
            log.info("查询参数：orgIdList：{},scItemCode:{},startTime:{},endTime:{}", JSON.toJSONString(orgIdList), scItemCode, startTime, endTime);

            // 计划调拨单（正向）
            SumAllocateOrderQuantityResponse planTransferEntity = this.sumAllocateOrderQuantity(
                    SumAllocateOrderQuantityRequest.builder().startTime(startTime).endTime(endTime).scItemId(scItemCode).applyOrgIdList(orgIdList).orderType("1").returnOrder(false).build());
            Integer planTransferCount = planTransferEntity.getQuantity() == null ? 0 : planTransferEntity.getQuantity();

            // 计划调拨单（退单）
            SumAllocateOrderQuantityResponse planTransferReverseEntity = this.sumAllocateOrderQuantity(
                    SumAllocateOrderQuantityRequest.builder().startTime(startTime).endTime(endTime).scItemId(scItemCode).applyOrgIdList(orgIdList).orderType("1").returnOrder(true).build());
            Integer planTransferReverseCount = planTransferReverseEntity.getQuantity() == null ? 0 : planTransferReverseEntity.getQuantity();

            // 总部销售调拨单（正向）-不包含从总部销售调拨单直接创建的订单
            SumAllocateOrderQuantityResponse salesTransferEntity = this.sumAllocateOrderQuantity(SumAllocateOrderQuantityRequest.builder().startTime(startTime).endTime(endTime).scItemId(scItemCode).applyOrgIdList(orgIdList).orderType("2").returnOrder(false).build());
            Integer salesTransferCount = salesTransferEntity.getQuantity() == null ? 0 : salesTransferEntity.getQuantity();

            // 总部销售调拨单（退单）
            SumAllocateOrderQuantityResponse salesTransferReverseEntity = this.sumAllocateOrderQuantity(
                    SumAllocateOrderQuantityRequest.builder().startTime(startTime).endTime(endTime).scItemId(scItemCode).applyOrgIdList(orgIdList).orderType("2").returnOrder(true).build());
            Integer salesTransferReverseCount = salesTransferReverseEntity.getQuantity() == null ? 0 : salesTransferReverseEntity.getQuantity();

            // 组合结果
            return Result.success(
                    SurplusAllocateQuantityResponse.builder()
                            .planTransferCount(planTransferCount)
                            .planTransferReverseCount(planTransferReverseCount)
                            .salesTransferCount(salesTransferCount)
                            .salesTransferReverseCount(salesTransferReverseCount)
                            .build());
        }

        @Override
        public GetBusinessScenarioResponse getBusinessScenario (AllocateOrder allocateOrder){
            log.info("GetBusinessScenario request:{}", JSONObject.toJSONString(allocateOrder));

            // 只处理总部销售订单
            if (!AllocateOrderTypeEnum.HEADQUARTER_SALES.getType().equals(allocateOrder.getType())) {
                return GetBusinessScenarioResponse.builder().build();
            }

            // 是否直发客户
            Boolean isDTC = allocateOrder.getIsDTC();
            // 是否为退单
            Boolean returnOrder = allocateOrder.getReturnOrder();
            // 发货库区ID
            String shipAreaId = allocateOrder.getShipAreaId();

            Integer shipAreaType = 0;
            log.info("shipAreaType:{}", shipAreaType);
            Result<List<WarehouseInfoDTO>> warehouseInfoResult = unifiedInventoryService.queryCargoZoneById2(QueryCargoZoneById2Request.builder().cargoZoneIdList(Arrays.asList(shipAreaId)).build());
            if (warehouseInfoResult.getTotal() > 0) {
                shipAreaType = warehouseInfoResult.getResult().get(0).getType();
            }

            String businessScenario = "";
            if (shipAreaType == 5 && !isDTC && !returnOrder) {// 工厂仓
                businessScenario = "F-B";
            } else if (shipAreaType == 2 && !isDTC && !returnOrder) { // 共享仓
                businessScenario = "F1-B";
            } else if (isDTC && !returnOrder) {
                businessScenario = "F-b";
            } else if (returnOrder) {
                businessScenario = "B/b—F/F1";
            }
            log.info("GetBusinessScenario response:{}", businessScenario);
            return GetBusinessScenarioResponse.builder().businessScenario(businessScenario).build();
        }

        //查询冻结及未确认金额
        @Override
        public Result<FrozenAndUnconfirmedAmountResponse> queryFrozenAndUnconfirmedAmount
        (QueryFrozenAndUnconfirmedAmountRequest queryFrozenAndUnconfirmedAmountRequest){
            log.info("queryFrozenAndUnconfirmedAmount_request:{}", JSON.toJSONString(queryFrozenAndUnconfirmedAmountRequest));
            Result<FrozenAndUnconfirmedAmountResponse> result = allocateOrderReadRepository.queryFrozenAndUnconfirmedAmount(queryFrozenAndUnconfirmedAmountRequest.getCompanyId());
            log.info("queryFrozenAndUnconfirmedAmount_response:{}", result);
            return result;
        }

        private static String getLogStatus(String features){
            if (StringUtils.isBlank(features)){
                return null;
            }
            Map<String,String> map = JSON.parseObject(features, Map.class);
            if (MapUtils.isNotEmpty(map)){
                return map.get("status");
            }
            return null;
        }


}
